How do I get the full path to a Perl script that is executing?
Solution 1:
There are a few ways:
-
$0
is the currently executing script as provided by POSIX, relative to the current working directory if the script is at or below the CWD - Additionally,
cwd()
,getcwd()
andabs_path()
are provided by theCwd
module and tell you where the script is being run from - The module
FindBin
provides the$Bin
&$RealBin
variables that usually are the path to the executing script; this module also provides$Script
&$RealScript
that are the name of the script -
__FILE__
is the actual file that the Perl interpreter deals with during compilation, including its full path.
I've seen the first three ($0
, the Cwd
module and the FindBin
module) fail under mod_perl
spectacularly, producing worthless output such as '.'
or an empty string. In such environments, I use __FILE__
and get the path from that using the File::Basename
module:
use File::Basename;
my $dirname = dirname(__FILE__);
Solution 2:
$0 is typically the name of your program, so how about this?
use Cwd 'abs_path';
print abs_path($0);
Seems to me that this should work as abs_path knows if you are using a relative or absolute path.
Update For anyone reading this years later, you should read Drew's answer. It's much better than mine.
Solution 3:
use File::Spec;
File::Spec->rel2abs( __FILE__ );
http://perldoc.perl.org/File/Spec/Unix.html
Solution 4:
I think the module you're looking for is FindBin:
#!/usr/bin/perl
use FindBin;
$0 = "stealth";
print "The actual path to this is: $FindBin::Bin/$FindBin::Script\n";
Solution 5:
You could use FindBin, Cwd, File::Basename, or a combination of them. They're all in the base distribution of Perl IIRC.
I used Cwd in the past:
Cwd:
use Cwd qw(abs_path);
my $path = abs_path($0);
print "$path\n";