0

这是我的脚本的一部分:

foreach $i ( @contact_list ) {

    print "$i\n";

    $e = "zcat $file_list2| grep $i";
    print "$e\n";

    $f = qx($e);
    print "$f";                                       
}

$e打印正确,但$f即使$file_list2匹配. 也会给出一个空行$i

谁能告诉我为什么?

4

2 回答 2

0

您的问题让我们猜测很多事情,但更好的整体方法似乎是只打开文件一次,并在 Perl 本身中处理每一行。

open(F, "zcat $file_list |") or die "$0: could not zcat: $!\n";
LINE:
while (<F>) {
    ######## FIXME: this could be optimized a great deal still
    foreach my $i (@contact_list) {
        if (m/$i/) {
            print $_;
            next LINE;
        }
    }
}
close (F);

如果您想从内部循环中挤出更多内容,请在循环@contact_list之前将正则表达式编译到一个单独的数组中,或者如果您只关心其中一个是否匹配,则可以将它们组合成一个正则表达式。另一方面,如果您只想在知道它们是什么的情况下仅在最后打印一个模式的所有匹配项,则将每个搜索表达式的匹配项收集到一个数组中,然后循环它们并在您对整个输入集进行 grep 后打印文件。

如果没有有关内容的信息,您的问题是不可重现的$i,但我可以猜测它包含一些 shell 元字符,导致它在grep运行之前由 shell 处理。

于 2016-09-26T11:14:54.537 回答
0

总是使用 Perl 的 grep 而不是使用 pipe 更好:

@lines = `zcat $file_list2`;    # move output of zcat to array
die('zcat error') if ($?);      # will exit script with error if zcat is problem
# chomp(@lines)                 # this will remove "\n" from each line

foreach $i ( @contact_list ) {

    print "$i\n";

    @ar = grep (/$i/, @lines);
    print @ar;
#   print join("\n",@ar)."\n";      # in case of using chomp
}

最好的解决方案不是调用 zcat,而是使用 zlib 库: http: //perldoc.perl.org/IO/Zlib.html

use IO::Zlib;

# ....
# place your defiiniton of $file_list2 and @contact list here.
# ...

$fh = new IO::Zlib; $fh->open($file_list2, "rb")
    or die("Cannot open $file_list2");
@lines = <$fh>;
$fh->close;

#chomp(@lines);                    #remove "\n" symbols from lines
foreach $i ( @contact_list ) {

    print "$i\n";
    @ar = grep (/$i/, @lines);
    print (@ar);
#   print join("\n",@ar)."\n";    #in case of using chomp
}
于 2016-09-27T11:40:29.697 回答