Perl open(FH,"grep foo bar |") - 当grep什么都不返回时,关闭FH失败

Cha*_*hap 0 perl pipe

我正在打开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: $!";
Run Code Online (Sandbox Code Playgroud)

在这里,我调用foo来搜索'warn':

~/private/perl$ ./foo warn
    : use warnings;
    : close $grep_h or warn "Error closing grep pipe: $!";
Run Code Online (Sandbox Code Playgroud)

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

~/private/perl$ ./foo blarg
Error closing grep pipe:  at ./foo line 16.
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?

ike*_*ami 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;
Run Code Online (Sandbox Code Playgroud)

你会得到"Child from error 1",因为grep它找不到匹配项时返回错误.

$ echo foo | grep foo
foo

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

$ echo foo | grep bar

$ echo $?
1
Run Code Online (Sandbox Code Playgroud)