http://www.perlmonks.org?node_id=1092109

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 (Archbishop) 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 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 (Patriarch) 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