2009-05-14

Standard I/O Redirection in Perl

This is an excerpt from the Perl manuals at perlDoc.perl.org concerning redirection of STDOUT and STDERR in Perl:

Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together:

$output = `cmd 2>&1`;

To capture a command's STDOUT but discard its STDERR:

$output = `cmd 2>/dev/null`;

To capture a command's STDERR but discard its STDOUT (ordering is important here):

$output = `cmd 2>&1 1>/dev/null`;

To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:

$output = `cmd 3>&1 1>&2 2>&3 3>&-`;

To read both a command's STDOUT and its STDERR separately, it's easiest to redirect them separately to files, and then read from those files when the program is done:

system("program args 1>program.stdout 2>program.stderr");

The STDIN filehandle used by the command is inherited from Perl's STDIN. For example:

open BLAM, "blam" || die "Can't open: $!";
    open STDIN, "<&BLAM";

    print `sort`;

will print the sorted contents of the file "blam".

The I/O Operators manual also has some interesting information about standard file I/O in Perl.