www.rodneybeede.com "I would love to change the world, but they won't give me the source code" - unknown

Dynamically obtain Perl script's directory and filename - Last Modified 2015-03-20 21:04 UTC - Created 2009-04-27 21:28 UTC

Note that this only works if you didn't use the perl -e or someprog | perl piping method.

A common method available since perl 5.8: FindBin

An alternative method:

It will still work regardless of the calling parent attempting to set $0 to something else in an exec call. This is because Perl always forces $0 to the value given when you passed in a script for it to run. This code also resolves any relative pathnames to their absolute counter parts.

my $scriptDirectory = File::Basename::dirname(File::Spec->rel2abs($0));
my $scriptFilename = File::Basename::basename(File::Spec->rel2abs($0));