Perl - 我可以获得与脚本驻留位置及其执行位置相关的路径吗?
我正在寻找一种方法来获取两条信息:
- 脚本所在位置的完整路径,包括其文件名
- 执行脚本的完整路径
我知道您可以使用 $0
来获取文件名,但是还有 Perl 原生的其他保留变量可以提供我要查找的内容吗?
我宁愿不使用任何特殊模块,但如果这是唯一的方法,那就这样吧。
I'm looking for a way to get two pieces of information:
- The full path of where a script resides including its filename
- The full path of where a script was executed from
I know you can use $0
to get the file name, but are there any other reserved variables that are native to Perl that will give me what I'm looking for?
I'd rather not use any special modules, but if it is the only way, then so be it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
FindBin
和Cwd
:示例输出(脚本保存为
/tmp/test.pl
):Using
FindBin
andCwd
:Sample output (script saved as
/tmp/test.pl
):根据需要打印脚本的完整路径,包括文件名。
prints full path to your script including filename as you want.
PWD
环境变量保存当前工作目录,该目录应该是执行脚本的路径。您可以使用
$ENV{PWD}
和$0
导出脚本的完整路径编辑:提供示例代码,因为有些人很难相信这是可能的:
我可能没有捕获所有可能的情况,但这应该非常接近:
测试运行的输出:
the
PWD
environment variable holds the current working directory, which should be the path the script was executed from.You can derive the full path of the script with
$ENV{PWD}
and$0
Edit: providing sample code since it is hard for some to believe this is possible:
I may not have caught all the possible cases, but this should get very close:
Output from test runs:
这可以通过内置的 $FindBin::Bin 变量来实现(参见 perldoc FindBin):
This is available with the built-in $FindBin::Bin variable (see perldoc FindBin):
您询问了特殊的 Perl 内容,但没有人提到
__FILE__
。检查 perldata 以获得更多信息。当我有文件/脚本/模块的相关子树时,我经常使用这个习惯用法 -You asked about special Perl stuff and no one has mentioned
__FILE__
. Check perldata for it and more. I use this idiom often when I have a related subtree of files/scripts/modules–对于也处理符号链接的解决方案,
For an solution that also handles symlinks,
您可以使用核心
Cwd
模块来获取脚本被执行,核心File::Spec
模块找到脚本的完整路径:You can use the core
Cwd
module to get the directory from which the script was executed, and the coreFile::Spec
module to find the whole path to the script: