我有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() and abs_path() are provided by the Cwd 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 模块和 FindBin 模块)在mod_perl下失败,产生了毫无价值的输出,例如'.'或空字符串.在这种环境下,我使用 __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脚本的完整路径?
发布评论