Reputation: 899
I am executing a diff
command in 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;
}
Here the diff
might have failed because of some reason. For example: the stderr showed that /usr/local/bin/diff: test.txt: No such file or directory. I want to read this message in the program. How I can find the stderr message of the diff
command (or grep
or any command I execute)?
Appreciate the help in advance.
Thanks, Mathew Liju
Upvotes: 3
Views: 2649
Reputation: 132758
This is answered in perlfaq8: How can I capture STDERR from an external command?
If I want to read STDOUT and STDERR of a process, I use IPC::Open3, which comes with Perl. That way, I don't have to merge those streams and later figure out what part of the output came from what.
I would try to avoid temporary files whenever possible (so no 2>file.txt
). That's just too much work and code when I can read STDERR directly.
Upvotes: 12
Reputation: 2995
There are several CPAN modules that make this easy and let you keep STDOUT and STDERR separate. For example, IO::CaptureOutput would let you do it like this (though you'll need to split the lines yourself):
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;
-- David
Upvotes: 4