If I am in some library code, how do I determine the path to the file of the code that is currently executing? I know how to get the path of the top perl file by looking at ARGV
, but if I load a library, how can that library know which path it is at?
The __FILE__
token will give you the full path including the file name. You can use File::Spec to split it into components:
my ($volume, $directory, $file) = File::Spec->splitpath(__FILE__);
The easiest way to find the filename of the current executable is with FindBin:
use FindBin;
use File::Spec;
print "the directory of my script is: " . $FindBin::Bin . "\n";
print "the base name of my script is: " . $FindBin::Script . "\n";
print "the canonical location of my script is: " . File::Spec->catfile($FindBin::Bin, $FindBin::Script) . "\n";
Internally, you can get at some of this information by looking at $0
(the name of the script as invoked at the command line), and __FILE__
, which is the name of the currently-executing file. (See perldoc perlvar.)
To extract the filename of the currently-executing module, start with examining __PACKAGE__
, do some substitution magic and then look up the filename in %INC
:
(my $filename = __PACKAGE__ ) =~ s#::#/#g;
$filename .= '.pm';
my $abs_filename = $INC{$filename};
I do this in one of my initialization libraries to find a configuration script in a path relative to the current module (I have several code branches installed side-by-side, each with slightly different configs):
# use the location of the current module as a guide for where to find configs
(my $filename = __PACKAGE__ ) =~ s#::#/#g;
$filename .= '.pm';
(my $path = $INC{$filename}) =~ s#/\Q$filename\E$##g; # strip / and filename
my $abs_config_file = File::Spec->catfile($path, $config_file);
MyApp->initialize($abs_config_file);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With