How can I read stderr when command execution fails in Perl?

I execute the command diffin perl.

my @lines = `/usr/local/bin/diff -udr \"$expected_file\" \"$gen_file\"`;

if ($? != 0)
{
    print ERRFILE "Diff between $expected_file and $gen_file failed\n";
    return $diff_err;
}

There diffmight be a crash for some reason. For example: stderr showed that / usr / local / bin / diff: test.txt: There is no such file or directory. I want to read this message in the program. How can I find the message stderr command diff(or grepor any command that I execute)?

Appreciate the help in advance.

Thanks Matthew Liju

+3
source share
2 answers

Perlfaq8 answers this: How can I grab STDERR from an external command?

STDOUT STDERR , IPC:: Open3, Perl. , , , .

, ( 2>file.txt). , STDERR.

+12

CPAN, STDOUT STDERR . , IO::CaptureOutput ( ):

use IO::CaptureOutput 'qxx';


my ($stdout, $stderr, $ok) = 
    qxx( qq(/usr/local/bin/diff -udr "$expected_file" "$gen_file") );

if (! $ok)
{
    print ERRFILE "Diff between $expected_file and $gen_file failed\n";
    return $stderr;
}

my @lines = split /\n/, $stdout;

-

+4

All Articles