0

我正在打开grep命令的管道并逐行读取结果。完成后,我关闭管道。如果grep找到任何东西,则close()正常完成。如果grep 没有找到任何东西,则close()不起作用。

这是演示问题的foo :

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

my $search = shift // die "Usage: foo search_string";

open my $grep_h, "grep '$search' ./foo |"
  or die "open grep failed: $!";

while (defined (my $line = <$grep_h>)) {
    chomp $line;
    say "\t: $line";
}
close $grep_h or warn "Error closing grep pipe: $!";

在这里,我调用foo来搜索“警告”:

~/private/perl$ ./foo warn
    : use warnings;
    : close $grep_h or warn "Error closing grep pipe: $!";

在这里,我调用foo来搜索“blarg”:

~/private/perl$ ./foo blarg
Error closing grep pipe:  at ./foo line 16.

为什么我会收到此错误?

4

1 回答 1

6

close($child)$?。如果$?非零,则返回 false。

close($grep_h);
die "Can't close: $!\n" if $? == -1;
die "Child died from signal ".($? & 0x7F)."\n" if $? & 0x7F;
die "Child exited from error ".($? >> 8)."\n" if $? >> 8;

您将收到“Child exited from error 1”,因为grep在找不到匹配项时会返回错误。

$ echo foo | grep foo
foo

$ echo $?    # Equivalent to Perl's $? >> 8
0

$ echo foo | grep bar

$ echo $?
1
于 2013-04-27T01:57:35.713 回答