Dynamically obtain Perl script's directory and filename

Last Modified: Fri, 20 Mar 2015 21:04:48 +0000 ; Created: Mon, 27 Apr 2009 21:28:48 +0000

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));