Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the directory of the current (not currently executing) file at runtime?

Tags:

perl

I have a .pm file, let's call it A.pm, that I am use-ing in another file B.pl, which lives in a separate directory. Inside A.pm, I would like to reference an external non-perl file that exists in same directory. To avoid hardcoding the path to that external file, I would like to get the directory in which A.pm lives at run time.

I've tried using $FindBin::Bin and File::Spec->rel2abs('.'), but I've learned that those point you to directory of the currently executing script, not the current file. $0 gives me the name of the currently executing script as well.

Is there a way to get the directory A.pm lives in aside from hardcoding the path in A.pm?

EDIT: I should also note that I've tried just referencing the external file with path relative to A.pm, but during execution, the code looks for the external file in directory where B.pl lives, so that doesn't work either.

like image 277
Jon G Avatar asked Dec 29 '25 03:12

Jon G


2 Answers

__FILE__ returns the path that was used to retrieve the file being executed. This means you could use the following:

use File::Basename qw( dirname );

dirname(__FILE__)

That will fail if a symlink was used to load the file, so one normally wants to resolve symlinks first.

use Cwd            qw( abs_path );
use File::Basename qw( dirname );

dirname(abs_path(__FILE__))

This is more important for a script than for a module because the odds of a symlink being used to load a module are quite low.

Warning: These can fail if the CWD changed since the module was loaded.

like image 103
ikegami Avatar answered Dec 31 '25 19:12

ikegami


If you've already use'd or require'd a module, the location of the file resides in %INC.

$ perl -MJSON -E 'say $INC{"JSON.pm"}'
/opt/share/perl5/site_perl/5.16/JSON.pm
like image 45
mob Avatar answered Dec 31 '25 17:12

mob