2014-10-28 43 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稱之爲失敗。