我想抑制子进程中的输出并只读取 stderr。 perlfaq8建议做以下事情:
# To capture a program's STDERR, but discard its STDOUT:
use IPC::Open3;
use File::Spec;
use Symbol qw(gensym);
open(NULL, ">", File::Spec->devnull);
my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
while( <PH> ) { }
waitpid($pid, 0);
但随后
perlcritic
在 using bareword file handles 上争论.我唯一能想到的就是
select
新打开的描述符到 /dev/null
而是在 STDOUT
, 像这样:# To capture a program's STDERR, but discard its STDOUT:
use IPC::Open3;
use File::Spec;
use Symbol qw(gensym);
open my $null, ">", File::Spec->devnull;
my $old_stdout = select( $null );
my $pid = open3(gensym, ">&STDOUT", \*PH, "cmd");
select( $old_stdout );
while( <PH> ) { }
waitpid($pid, 0);
但随后
perlcritic
不喜欢 using of select
.有没有更优雅的解决方案?
最佳答案
最小的变化只是通过将其更改为 *NULL 来使 open 中的 NULL 不再是一个裸词。
使用这种形式的句柄通常仍然被认为是糟糕的形式(因为它们是全局变量,尽管您可以通过对它们应用 local 来使它们稍微不那么全局)。因此,我建议将其更改为对所有句柄使用我的变量。看起来你也扔掉了标准输入文件句柄,这样也可以传递空文件句柄(注意我在读写模式下打开它)
use strict;
use warnings;
use IPC::Open3;
use File::Spec;
use Symbol qw(gensym);
open(my $null, '+>', File::Spec->devnull);
my $childErr = gensym;
my $pid = open3($null, $null, $childErr, "cmd");
while(<$childErr>) { }
waitpid($pid, 0);
关于perl - 将 IPC::Open3 与 perlcritic 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20393647/