Search code examples
perlperl-criticipcopen3

Use IPC::Open3 with perlcritic


I want to supress output in child process and read only stderr. perlfaq8 advises to do following:

# 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);

But then perlcritic argues on using bareword file handles.

The only thing i can devise is to select newly opened descriptor to /dev/null instead on STDOUT, like this:

# 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);

But then perlcritic doesn't like using of select. Is there more elegant solution?


Solution

  • The minimal change is just to make the use of NULL in open no longer a bareword by changing it to *NULL.

    It's still usually considered poor form to use handles of this form (Because they are global variables, though you can make them somewhat less global by applying local to them). So I would recommend changing it to instead use my variables for all the handles. It also looks like you're throwing away the stdin filehandle, so that too can be passed the null filehandle (note I'm opening it in read-write mode)

    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);