I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script $0
varies and sometimes contains the fullpath+filename
and sometimes just filename
. Because the working directory can vary as well I can't think of a way to reliably get the fullpath+filename
of the script.
Anyone got a solution?
Best Answer
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 CWDcwd()
,getcwd()
andabs_path()
are provided by theCwd
module and tell you where the script is being run fromFindBin
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
, theCwd
module and theFindBin
module) fail undermod_perl
spectacularly, producing worthless output such as'.'
or an empty string. In such environments, I use__FILE__
and get the path from that using theFile::Basename
module: