使用perl变量执行系统

cuc*_*bit 1 perl system

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

这完全符合我的perl脚本:

system("samtools", "sort", $file, "01_sorted.SNP");
Run Code Online (Sandbox Code Playgroud)

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

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

错误:

open: No such file or directory
Run Code Online (Sandbox Code Playgroud)

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

ike*_*ami 10

您在后一个代码段中出现了注入错误.通过这种方式,我的意思是当你构建shell命令时,你忘了将值转换为$file产生值的shell文字$file.这是非常满口的,所以我将在下面说明这意味着什么.


$file包含a b.txt.

my @cmd = ("samtools", "sort", $file, "01_sorted.SNP");
system(@cmd);
Run Code Online (Sandbox Code Playgroud)

相当于

system("samtools", "sort", "a b.txt", "01_sorted.SNP");
Run Code Online (Sandbox Code Playgroud)

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


my $cmd = "samtools sort $file 01_sorted.SNP";
system($cmd);
Run Code Online (Sandbox Code Playgroud)

相当于

system("samtools sort a b.txt 01_sorted.SNP");
Run Code Online (Sandbox Code Playgroud)

这将执行shell,将字符串作为执行命令传递.

反过来,shell将执行samtools,经过4sort,a,b.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);
Run Code Online (Sandbox Code Playgroud)

相当于

system("samtools sort 'a b.txt' 01_sorted.SNP");
Run Code Online (Sandbox Code Playgroud)

这将执行shell,将字符串作为执行命令传递.

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