develooper Front page | perl.perl5.porters | Postings from October 2007

Re: [perl #47031] Feature: three-argument open() for reading stderr, not stdout

Thread Previous
From:
David Nicol
Date:
October 30, 2007 22:00
Subject:
Re: [perl #47031] Feature: three-argument open() for reading stderr, not stdout
Message ID:
934f64a20710302200w11518c86s861bd8a46b3f686d@mail.gmail.com
On 10/30/07, via RT Ed Avis <perlbug-followup@perl.org> wrote:

> To read stdout from a command you can say
>
>     open FH, '-|', 'echo', 'hello';
>
> But this gives no straightforward way to read stderr.  You can go back
> to two-argument open() and use the shell to handle 2>&1, if on a
> platform that supports it.  But that no longer has the cleanliness of
> passing arguments directly in a perl list.
>
> There is IPC::Open3, but that is heavyweight for the case when all you
> want to do is read stderr, not set up a command with input piped both
> in and out.
>
> I hope it would be straightforward to add a feature like
>
>     open FH, '-2|', 'echo', 'hello'
>
> which gives you a filehandle reading the command's standard error, and
> leaves its standard output alone.

this gives you a stderr-capturing backtick variant kind of thing; but
the approach
can be adjusted to keep our end of the stderr pipe.

   sub GimmeStdErr(@){  # ... bangles, tangles and spaghetti!
         local *R, *W;
         pipe R,W;
         if(fork){
             close W;
             <R>
         }else{
             close R;
             open STDERR, ">&W";
             exec @_
         }
   };

Here's the tested version:
$ ls nonexistent
ls: cannot access nonexistent: No such file or directory

$ ls nonexistent > /dev/null
ls: cannot access nonexistent: No such file or directory

$ perl -le 'exec qw/ls nonexistent/'
ls: cannot access nonexistent: No such file or directory

$ perl -le 'pipe R,W; if(fork){close W; print "got: ".<R>}else{close R; open ST
DERR, ">&W"; exec qw/ls nonexistent/}'
got: ls: cannot access nonexistent: No such file or directory

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About