如何获取正在执行的Perl脚本的完整路径? [英] How do I get the full path to a Perl script that is executing?
问题描述
我有Perl脚本,需要在执行期间确定脚本的完整路径和文件名.我发现,取决于脚本的调用方式,$0
有所不同,有时包含fullpath+filename
,有时仅包含filename
.因为工作目录也可能变化,所以我想不出一种可靠地获取脚本fullpath+filename
的方法.
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.
有人解决了吗?
推荐答案
有几种方法:
-
$0
是POSIX提供的当前执行脚本,相对于当前工作目录(如果脚本位于CWD或以下) - 另外,
cwd()
,getcwd()
和abs_path()
由Cwd
提供模块,并告诉您脚本从何处运行 - 模块
FindBin
提供了$Bin
&通常是执行脚本的路径的$RealBin
变量;此模块还提供$Script
&$RealScript
是脚本的名称 -
__FILE__
是Perl解释器在处理期间处理的实际文件编译,包括其完整路径.
$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.
我看过前三个( $0
, Cwd
模块和 __FILE__
并使用 File::Basename
模块:
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__);
这篇关于如何获取正在执行的Perl脚本的完整路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!