【问题标题】:execute system with perl variable使用 perl 变量执行系统
【发布时间】:2014-10-28 17:22:26
【问题描述】:

我想在 perl 脚本中执行一个 bash 命令。我知道该怎么做,但是,当我尝试将命令保存在变量中然后执行它时......我遇到了问题。

这在我的 perl 脚本中完美运行:

system("samtools", "sort", $file, "01_sorted.SNP");

这不起作用,我想知道为什么,以及如何解决...:

my $cmd = "samtools sort $file 01_sorted.SNP";
print "$cmd\n";  # Prints the correct command BUT...
system($cmd);

错误:

open: No such file or directory

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: perl system


    【解决方案1】:

    你在后面的 sn-p 中有注入错误。我的意思是,当你构建你的 shell 命令时,你忘记将$file 的值转换为产生$file 值的shell 文字。这么多,所以我将在下面说明它的含义。


    $file 包含a b.txt

    my @cmd = ("samtools", "sort", $file, "01_sorted.SNP");
    system(@cmd);
    

    等价于

    system("samtools", "sort", "a b.txt", "01_sorted.SNP");
    

    这会执行samtools,并将三个字符串sorta b.txt01_sorted.SNP 作为参数传递给它。


    my $cmd = "samtools sort $file 01_sorted.SNP";
    system($cmd);
    

    等价于

    system("samtools sort a b.txt 01_sorted.SNP");
    

    这会执行shell,将字符串作为要执行的命令传递。

    反过来,shell 将执行samtools,将四个 字符串sortab.txt01_sorted.SNP 作为参数传递给它。

    samtools找不到文件a,所以报错。


    如果需要构建 shell 命令,请使用String::ShellQuote

    use String::ShellQuote qw( shell_quote );
    my $cmd = shell_quote("samtools", "sort", "a b.txt", "01_sorted.SNP");
    system($cmd);
    

    等价于

    system("samtools sort 'a b.txt' 01_sorted.SNP");
    

    这会执行shell,将字符串作为要执行的命令传递。

    反过来,shell 将执行samtools,将三个字符串sorta b.txt01_sorted.SNP 作为参数传递给它。

    【讨论】:

      【解决方案2】:

      open: No such file or directory 的错误看起来不像 perl 打印的错误,因为system 不会为您打印任何错误。这可能是由samtools 打印的,所以只需检查您的文件名——$file01_sorted.SNP——是否正确并且文件是否存在。此外,如果$file 包含空格,请将其名称放在命令行中的引号中。或者,更好的是,按照 cmets 中的建议使用 system(@args)

      如果您没有任何想法,请使用strace 运行您的脚本:

      strace -f -o strace.log perl yourscript.pl
      

      并检查strace.log 以查看哪个open 调用失败。

      【讨论】:

        猜你喜欢
        • 2016-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2017-06-11
        相关资源
        最近更新 更多