【问题标题】:Perl -How do i pass complete directory path name into perl scriptPerl - 我如何将完整的目录路径名传递给 perl 脚本
【发布时间】:2014-10-03 20:31:54
【问题描述】:

我有一个 perl 脚本,它从“/root/pkt/sw/se/tool”路径执行,需要脚本内的完整目录路径。

你能告诉我如何获得完整的路径吗?

sample.pl

 our ($tool_dir);

 use strict;
 use warnings;
 BEGIN {
   $tool_dir = $0;
   my $home_path = $tool_dir
   $home_path =~ s|\w*/\w*/\w*$||;
   my $target_path ="obj/Linux-i686/usr/share/ddlc/lib";
   $lib_dir = "$home_path$target_path";
   unshift(@INC, $lib_dir);
 }

我正在从“pkt/sw/se/tool”路径执行这个脚本,但这里我只得到“pkt/sw/se/tool”而不是“/root/pkt/sw/se/tool”

我的 perl 脚本在 /root/pkt/sw/se/tools/sample.pl 下可用

【问题讨论】:

    标签: perl


    【解决方案1】:

    您可以使用 CWD 模块 (http://perldoc.perl.org/Cwd.html)(代码取自该页面)

    use Cwd;
    my $dir = getcwd;
    use Cwd 'abs_path';
    my $abs_path = abs_path($file);
    

    或者你可以执行 pwd 命令

    $cwd = `pwd`;
    

    如果您只想要目录,而不是完整路径,您可以在 Print current directory using Perl 上查看现有答案

    【讨论】:

    • 感谢您的解决方案
    • 在第 3 行为什么要重复声明 use Cwd 'abs_path';?在工作的第 1 行声明 abs_path
    • @Hussain,查看我链接的原始答案并在那里提问:-)
    【解决方案2】:

    使用已经提到的模块之一,切勿使用反引号 - 除非您完全了解这样做的风险和影响。如果您确实想运行“pwd”,请通过 IPC::Run3 之类的方式调用它。

    例子:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Cwd;
    use IPC::Run3;
    
    # CWD
    my $working_dir_cwd = getcwd; 
    print "Woring Dir (Cwd): $working_dir_cwd\n";
    
    # IPC::Run3
    my ($in, $out, $err);
    my @command = qw/pwd/;
    
    run3 \@command, $in, \$out, \$err or die $?;
    
    print "Working Dir (pwd): $out\n";
    

    【讨论】:

    • 你能告诉我如何通过 IPC::Run 使用 'pwd' 吗?
    • 对不起,我的意思是 IPC::Run3。看一下示例脚本(编辑)。您会看到调用 Cwd 的代码要少得多 - 但 IPC::Run3 对于安全运行命令(简单或复杂)和捕获结果非常有用。
    【解决方案3】:

    您可以使用FindBin 来定位原始perl 脚本的目录。

    use FindBin;
    use lib "$FindBin::Bin/../../../obj/Linux-i686/usr/share/ddlc/lib";
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 2012-12-08
      • 2010-09-10
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      相关资源
      最近更新 更多