我有 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 脚本的完整路径?
发布评论