2014-10-28 42 views
0

我想在perl脚本中执行一个bash命令。我知道如何做到这一点,但是,当我尝试将命令保存在一个变量中,然后执行它...我有问题。用perl变量执行系统

这是我工作的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); 

ERROR:

open: No such file or directory 

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

+0

显示'$ file'的内容。 – toolic 2014-10-28 17:34:48

回答

7

您在后面的代码段中有注射错误。因此,我的意思是,当你建立你的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"); 

此执行壳,传递字符串作为要执行的命令。

反过来,外壳将执行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将执行samtools,将三个字符串sorta b.txt01_sorted.SNP作为参数传递给它。

1

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

如果你没有想法,使用strace运行脚本:

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

,并检查strace.log看到这open称之为失败。