Perl - 我可以获得与脚本所在位置以及脚本执行位置相关的路径吗?

时间:2011-01-26 20:33:58

标签: perl path directory filenames reserved-words

我正在寻找获取两条信息的方法:

  • 脚本所在的完整路径,包括其文件名
  • 执行脚本的完整路径

我知道您可以使用$0来获取文件名,但是Perl原生的任何其他保留变量是否会为我提供我想要的内容?

我宁愿不使用任何特殊模块,但如果这是唯一的方法,那就这样吧。

7 个答案:

答案 0 :(得分:7)

使用FindBinCwd

#!/usr/bin/env perl

use strict;
use warnings;

use Cwd        ();
use FindBin    ();
use File::Spec ();

my $full_path = File::Spec->catfile( $FindBin::Bin, $FindBin::Script );
my $executed_from_path = Cwd::getcwd();

print <<OUTPUT;
Full path to script: $full_path
Executed from path:  $executed_from_path
OUTPUT

示例输出(脚本保存为/tmp/test.pl):

alanhaggai@love:/usr/share$ /tmp/test.pl 
Full path to script: /tmp/test.pl
Executed from path:  /usr/share

答案 1 :(得分:3)

use File::Spec;

print File::Spec->rel2abs($0);

打印脚本的完整路径,包括您想要的文件名。

答案 2 :(得分:2)

PWD环境变量包含当前工作目录,该目录应该是脚本执行的路径。

您可以使用$ENV{PWD}$0

派生脚本的完整路径

修改:提供示例代码,因为有些人很难相信这是可能的:

我可能没有抓住所有可能的情况,但这应该非常接近:

use strict;
use warnings;

print "PWD: $ENV{PWD}\n";
print "\$0: $0\n";

my $bin = $0;
my $bin_path;

$bin =~ s#^\./##; # removing leading ./ (if any)

# executed from working directory
if ($bin !~ m#^/|\.\./#) {
  $bin_path = "$ENV{PWD}/$bin";
}
# executed with full path name
elsif ($bin =~ m#^/#) {
  $bin_path = $0;
}
# executed from relative path
else {
  my @bin_path = split m#/#, $bin;
  my @full_path = split m#/#, $ENV{PWD};

  for (@bin_path) {
    next if $_ eq ".";
   ($_ eq "..") ? pop @full_path : push @full_path, $_;
  }
  $bin_path = join("/", @full_path);
}

print "Script Path: $bin_path\n";

测试运行的输出:

PWD: /tmp
$0: ../home/cmatheson/test.pl
Script Path: /home/cmatheson/test.pl

PWD: /home/cam
$0: ./test.pl
Script Path: /home/cam/test.pl

PWD: /usr/local
$0: /home/cam/test.pl
Script Path: /home/cam/test.pl

PWD: /home/cam/Desktop/foo
$0: ../../src/./git-1.7.3.2/../../test.pl
Script Path: /home/cam/test.pl

答案 3 :(得分:2)

这可以使用内置的$ FindBin :: Bin变量(参见perldoc FindBin):

use FindBin;
use File::Spec;

print "the location of my script is: ", $FindBin::Bin, "\n";
print "the basename of my script is: ", $FindBin::Script, "\n";
print "the full path (symlinks resolved) of my script is: ", File::Spec->catfile($FindBin::RealBin, $FindBin::RealScript), "\n";

答案 4 :(得分:2)

对于也处理符号链接的解决方案,

use Cwd            qw( realpath );
use File::Basename qw( dirname );

# Look for modules in the same dir as the script.
use lib dirname(realpath($0));

答案 5 :(得分:1)

你问过特殊的Perl内容,没有人提到__FILE__。检查perldata以及更多内容。当我有一个相关的文件/脚本/模块子树时,我经常使用这个习语 -

use Path::Class qw( file );
use File::Spec;

my $self_file = file( File::Spec->rel2abs(__FILE__) );
print
    " Full path: $self_file", $/,
    "Parent dir: ", $self_file->parent, $/,
    " Just name: ", $self_file->basename, $/;

答案 6 :(得分:0)

您可以使用核心Cwd模块获取执行脚本的目录,使用核心File::Spec模块查找脚本的完整路径:

#!perl

use strict;
use warnings;
use Cwd;
use File::Spec;

my $dir = getcwd();
print "Dir: $dir\n";

print "Script: " . File::Spec->rel2abs($0) . "\n";