Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Unable to redirect stderr to stdout

by suman583 (Initiate)
on Jul 03, 2014 at 06:37 UTC ( #1092109=perlquestion: print w/replies, xml ) Need Help??

suman583 has asked for the wisdom of the Perl Monks concerning the following question:

I want to capture both STDERR and STDOUT for my command execution. I am using Bourne shell and having the below below peace of code in my perl file. $result = `$command 2>&1`; I get only STDOUT in $result. $result is empty when there is a error. Can someone please help on this?

Replies are listed 'Best First'.
Re: Unable to redirect stderr to stdout
by Athanasius (Bishop) on Jul 03, 2014 at 06:56 UTC

    Hello suman583, and welcome to the Monastery!

    I can’t test the Bourne shell, as I’m currently on Windows. But for a portable solution, use the CPAN module Capture::Tiny:

    use Capture::Tiny ':all'; ... my ($stdout, $stderr, @results) = capture { ... };

    Or, if you want the output to STDERR interleaved with the output to STDOUT:

    my $merged = capture_merged { ... };

    (But note the caveat in the documentation: “STDOUT and STDERR output in the merged result are not guaranteed to be properly ordered due to buffering.”)

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Unable to redirect stderr to stdout
by zentara (Archbishop) on Jul 03, 2014 at 08:46 UTC
Re: Unable to redirect stderr to stdout
by Corion (Pope) on Jul 03, 2014 at 07:00 UTC

    Are you sure that this is a problem with Perl? Does the command line work outside of Perl?

Re: Unable to redirect stderr to stdout
by pvaldes (Chaplain) on Jul 03, 2014 at 09:53 UTC

    try with system()

    perl -e 'my $result = system("ls 2>&1"); print $result;'

    But this should be ok, also. There is something here that we don't know

    perl -e 'my $result = `ls -3 2>&1`; print $result;' perl -e '`ls -3 2>&1`;' # <-- please note that this other one is silen +t

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1092109]
Approved by Athanasius
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2019-11-21 20:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (105 votes). Check out past polls.

    Notices?