SomethingSomething
SomethingSomething

Reputation: 12178

Perl: Getting STDERR of system call, separately from STDOUT

It is usually enough for me in Perl, to get a single string that contains STDOUT combined with STDERR. I do it this way:

my $stdout_and_stderr = `$cmd 2>&1`;

But now I need it in 2 separate strings - one for STDOUT and one for STDERR.

How can I do it in Perl?

Upvotes: 1

Views: 217

Answers (3)

SomethingSomething
SomethingSomething

Reputation: 12178

Actually I found a simpler way to catch only STDERR. Catch STDERR and throw STDOUT away:

$output = `cmd 2>&1 1>/dev/null`;

You can also do the opposite - throw STDERR away, such that it is even not printed to the shell:

$output = `cmd 2>/dev/null`; 

If you need to catch both of them separately, use one of the other answers in this thread. They are very good

Upvotes: 0

ikegami
ikegami

Reputation: 385506

use IPC::Run3 qw( run3 );
run3 [ 'sh', '-c', $cmd ], undef, my $stdout, my $stderr;

Upvotes: 3

serenesat
serenesat

Reputation: 4709

Here is an example.

#!/usr/bin/perl
use warnings;
use strict;
use IPC::Open3;

my $cmd = 'ls -la';

my $pid = open3(\*WRITER, \*READER, \*ERROR, $cmd);
#if \*ERROR is 0, stderr goes to stdout

while( my $output = <READER> )
{
    print "output->$output";
}

while( my $errout = <ERROR> )
{
    print "err->$errout";
}

waitpid( $pid, 0 ) or die "$!\n";
my $retval =  $?;
print "retval-> $retval\n";

Upvotes: 0

Related Questions