earth tech

[software and hardware technology originating from or otherwise pertinent to planet earth]

use these buttons to share this blog on portal sites:

Add to Google

Thursday, May 14, 2009

 

Standard I/O Redirection in Perl

http://perldoc.perl.org/perlop.html#Quote-Like-Operators

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.

Labels: , , , , ,

Archives

2006/12   2007/01   2007/05   2007/06   2007/07   2007/08   2007/10   2008/01   2008/02   2008/03   2008/05   2008/11   2008/12   2009/01   2009/02   2009/03   2009/04   2009/05   2009/07   2009/09   2009/10   2009/11   2009/12   2010/01  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]