【发布时间】:2016-02-11 19:42:43
【问题描述】:
在 Perl 中,读取子进程的 STDOUT 的一种方法是使用open:
open(PIPE, "ls -l |");
不过,我一直在寻找一种更面向对象的方式来执行此操作,并且我一直在使用 IO::Pipe 并取得了一些成功。不过,我想检测错误,特别是如果命令不可执行。不过,我不知道如何通过IO::Pipe 做到这一点。这是我所拥有的:
use strict;
use warnings;
use IO::Pipe;
my($cmd) = join (" ", @ARGV);
open(PIPE, "$cmd |") || die qq(error opening PIPE);
while (<PIPE>) {
chomp;
print "DBG1: $_\n";
}
close PIPE;
my($pipe) = IO::Pipe->new();
$pipe->reader($cmd);
die qq(error opening IO::Pipe) if $pipe->eof();
while (<$pipe>) {
chomp;
print "DBG2: $_\n";
}
$pipe->close();
如果子进程命令无效,两个检查都会正确die。但是,如果子进程没有输出,eof() 会报错,即使命令本身没问题:
$ perl pipe.pl "ls -l >/dev/null"
error opening IO::Pipe at pipe.pl line 20.
一堆问题,然后:
在 Perl 中是否有一种合理的 OO 方式从子进程中读取? IO::Pipe 是正确使用的工具吗?如果是这样,我如何检查以确保成功创建子流程命令?如果没有,我应该使用什么?我不想写子进程,所以我不认为我想要IPC::Open2 或IPC::Open3。如果可能的话,我更喜欢使用核心模块。
【问题讨论】: