Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do I get the directory or path of the current executing code?

Tags:

perl

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?

like image 224
Ross Rogers Avatar asked Mar 08 '10 17:03

Ross Rogers


2 Answers

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__);
like image 184
Michael Carman Avatar answered Sep 28 '22 05:09

Michael Carman


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);
like image 44
Ether Avatar answered Sep 28 '22 04:09

Ether