Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you capture stderr, stdout, and the exit code all at once, in Perl?

Is it possible to run an external process from Perl, capture its stderr, stdout AND the process exit code?

I seem to be able to do combinations of these, e.g. use backticks to get stdout, IPC::Open3 to capture outputs, and system() to get exit codes.

How do you capture stderr, stdout, and the exit code all at once?

like image 451
Scooby Avatar asked Sep 20 '08 19:09

Scooby


1 Answers

(Update: I updated the API for IO::CaptureOutput to make this even easier.)

There are several ways to do this. Here's one option, using the IO::CaptureOutput module:

use IO::CaptureOutput qw/capture_exec/;  my ($stdout, $stderr, $success, $exit_code) = capture_exec( @cmd ); 

This is the capture_exec() function, but IO::CaptureOutput also has a more general capture() function that can be used to capture either Perl output or output from external programs. So if some Perl module happens to use some external program, you still get the output.

It also means you only need to remember one single approach to capturing STDOUT and STDERR (or merging them) instead of using IPC::Open3 for external programs and other modules for capturing Perl output.

like image 179
xdg Avatar answered Oct 17 '22 08:10

xdg