Reputation: 5435
I'd like a native way to fix this problem...
I have a perl command that makes a call that, sometimes, prints out text directly to the console.
I want something like this:
$text = get_output_from(MagicCommandICan'tChange());
if ($text neq "a specific value") {
print $text;
}
Any way to do this?
Upvotes: 3
Views: 2810
Reputation: 15381
use IO::CaptureOutput qw(capture qxx qxy);
# STDOUT and STDERR separately
capture { noisy_sub(@args) } \$stdout, \$stderr;
Upvotes: 7
Reputation:
I'm assuming this Perl script is calling an external executable. If the output is being printed on stdout, you can use the backtick operators or qx
to run the command and capture the output. On a Unix system, you could use system()
and redirect the output to /dev/null
with the >
operator. You can also call open
with the command:
If the filename begins with '|', the filename is interpreted as a command to which output is to be piped, and if the filename ends with a '|', the filename is interpreted as a command that pipes output to us. See "Using open() for IPC" in perlipc for more examples of this. (You are not allowed to "open" to a command that pipes both in and out, but see IPC::Open2, IPC::Open3, and "Bidirectional Communication with Another Process" in perlipc for alternatives.)
Finally, you could close and reopen the STDOUT and STDERR filehandles (edit: IO::CaptureOutput
was recommended below). This is kind of weird, though; I wouldn't recommend it as the best alternative.
Upvotes: 2