我的 AWK 命令是:
awk'BEGIN {count=0} {count=count+($3-$2)} END {print count}' zebrafish
如何在 Perl 脚本中使用它?
我认为没有必要使用awkwithin perl。相同的功能可以完全实现perl如下
open my $fopen, '<', zebrafish or die $!;
my $count = 0;
while (<$fopen>) {
$count += $3-$2 if /(\S+)\s+(\S+)\s+(\S+)/;
}
print "count = $count\n";
close $fopen;
如果你还想用awk
您可以使用函数在此处从脚本system调用任何 shell 命令awkPerl
system("<awk_command>");
如果您希望输出awk存储在内部变量中,请perl使用
my $awk_output = `<awk_command>`;
附带说明一下,您的awk命令可以压缩为
awk'{count+=($3-$2)} END {print count}' zebrafish
为什么要同时使用 Perl 和 AWK?即使已经编写了 AWK 代码,如果您使用 Perl 对其进行扩展,将其翻译成 Perl 也可能是有意义的。例如:
sub count_diffs($filename) {
open my $f, "<$filename";
my $count = 0;
while (<$f>) {
my @F = split ' ';
$count += $F[2]-$F[1];
}
return $count;
}
my $count = count_diffs('zebrafish');
您还可以使用命令行选项来编写一个 Perl 单行器,它执行 AWK 代码的功能:
perl -lane '$count += $F[2]-$F[1]; END {print $count}'
但是在这种形式下,嵌入到更大的 Perl 程序中并不比 AWK 代码容易得多。
您可以使用:
system("command here"); #will return 0 on success
#or
open my $out,"command here |"; while(my $line=<$out>){print $line;}
#or
my $out=`command`;
#or
exec("command here"); #probably you don't want it!
When Perl first came about, it was used as more powerful awk replacement.
Because of this need, Perl actually comes with utility a2p, which is designed just for this purpose - it stands for awk to perl.
I tried to save your script into a file, and run it through a2p, and it worked fine - generated working Perl script. It was not very short (about 20 lines), but it worked.
Perl 中的命令应该是:
system("awk 'BEGIN {count =0} {count =count+(\$3-\$2)} END {print count}' zebrafish");
记住要转义字符$, ",我不知道还有什么\。当有疑问时,尝试逃跑;这就是哲学。