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

(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.

Leave a Comment