I need to find the full path to the Perl script I'm currently running, i.e.
我需要找到我正在运行的Perl脚本的完整路径,即
-
for ~/dir/my.pl I would need it to be "/home/user/dir/my.pl". The
$0
will give me "~/dir/my.pl".对于〜/ dir / my.pl我需要它是“/home/user/dir/my.pl”。 $ 0会给我“〜/ dir / my.pl”。
-
for ./my.pl I would still need "/home/user/dir/my.pl"
对于./my.pl我仍然需要“/home/user/dir/my.pl”
etc. Thanks!
6 个解决方案
#1
Use the FindBin module:
使用FindBin模块:
$ cat /tmp/foo/bar/baz/quux/prog
#! /usr/bin/perl
use FindBin;
print "$FindBin::Bin/$FindBin::Script\n";
$ PATH=/tmp/foo/bar/baz/quux prog
/tmp/foo/bar/baz/quux/prog
$ cd /tmp/foo/bar/baz/quux
$ ./prog
/tmp/foo/bar/baz/quux/prog
#2
It sounds like you're looking for the rel2abs function in File::Spec. For example:
听起来你正在寻找File :: Spec中的rel2abs函数。例如:
#!/usr/bin/perl
use File::Spec;
my $location = File::Spec->rel2abs($0);
print "$location\n";
This will resolve $0 in the way you describe:
这将以您描述的方式解决$ 0:
$ ./myfile.pl
/Users/myname/myfile.pl
$ ~/myfile.pl
/Users/myname/myfile.pl
Alternatively, you could use Cwd::abs_path in the exact same way.
或者,您可以以完全相同的方式使用Cwd :: abs_path。
#4
Looks like you just need to expand the paths to their absolute values. Check this article for how to do that.
看起来你只需要将路径扩展到它们的绝对值。查看本文以了解如何执行此操作。
#5
Use FindBin Module
使用FindBin模块
#6
Many of the concepts mentioned will break in case that the file itself is a symbolic link. I usually start my scripts in the following way:
如果文件本身是符号链接,则提到的许多概念将会中断。我通常以下列方式启动脚本:
use strict;
use English;
use warnings;
use Cwd qw(realpath);
use File::Basename;
use lib &File::Basename::dirname(&Cwd::realpath($PROGRAM_NAME));
Hopefully this helps.
希望这会有所帮助。
#1
Use the FindBin module:
使用FindBin模块:
$ cat /tmp/foo/bar/baz/quux/prog
#! /usr/bin/perl
use FindBin;
print "$FindBin::Bin/$FindBin::Script\n";
$ PATH=/tmp/foo/bar/baz/quux prog
/tmp/foo/bar/baz/quux/prog
$ cd /tmp/foo/bar/baz/quux
$ ./prog
/tmp/foo/bar/baz/quux/prog
#2
It sounds like you're looking for the rel2abs function in File::Spec. For example:
听起来你正在寻找File :: Spec中的rel2abs函数。例如:
#!/usr/bin/perl
use File::Spec;
my $location = File::Spec->rel2abs($0);
print "$location\n";
This will resolve $0 in the way you describe:
这将以您描述的方式解决$ 0:
$ ./myfile.pl
/Users/myname/myfile.pl
$ ~/myfile.pl
/Users/myname/myfile.pl
Alternatively, you could use Cwd::abs_path in the exact same way.
或者,您可以以完全相同的方式使用Cwd :: abs_path。
#3
You should take a look at FindBin or FindBin::Real.
你应该看看FindBin或FindBin :: Real。
#4
Looks like you just need to expand the paths to their absolute values. Check this article for how to do that.
看起来你只需要将路径扩展到它们的绝对值。查看本文以了解如何执行此操作。
#5
Use FindBin Module
使用FindBin模块
#6
Many of the concepts mentioned will break in case that the file itself is a symbolic link. I usually start my scripts in the following way:
如果文件本身是符号链接,则提到的许多概念将会中断。我通常以下列方式启动脚本:
use strict;
use English;
use warnings;
use Cwd qw(realpath);
use File::Basename;
use lib &File::Basename::dirname(&Cwd::realpath($PROGRAM_NAME));
Hopefully this helps.
希望这会有所帮助。