#!/usr/bin/env perl use warnings; use strict; use IPC::Open3; use Symbol qw(gensym); use POSIX qw(:sys_wait_h); # I'm sometimes using perl 5.8.5, so //'' unavailable # verified later on 5.14.2 sub defor($) { defined($_[0]) ? $_[0] : '' } foreach my $run (1..3) { my ($out, $err) = ('',''); my ($fhi, $fho, $fhe) = ($run == 1) ? (undef, undef, undef) : # when fhe==undef goes to open3, STDERR will be redirected to STDOUT ($run == 2) ? (undef, undef, gensym) : # this keeps STDERR and STDOUT separate (gensym, gensym, gensym) ; # as does this, the first two gensym are unecessary, but the third is needed my $pid = open3( $fhi, $fho, $fhe, qq[cat - ; perl -le 'print STDERR "this should be STDERR (run#$run)...\nand so should this (run#$run)\n"'] ); print { $fhi } "[run#$run] This should be STDOUT\n"; close($fhi); $out .= join '', map { s/^/STDOUT> / if $_ ne $/; $_ } readline($fho) if defined $fho; $err .= join '', map { s/^/STDOUT> / if $_ ne $/; $_ } readline($fhe) if defined $fhe; print "Read STDOUT:\n$out\n" if length($out); print "Read STDERR:\n$err\n" if length($err); printf "run#%d --- fhi='%s' fho='%s' fhe='%s'\n", $run, defor $fhi, defor $fho, defor $fhe; print "="x75, "\n\n"; } __END__ Read STDOUT: STDOUT> [run#1] This should be STDOUT STDOUT> this should be STDERR (run#1)... STDOUT> and so should this (run#1) run#1 --- fhi='GLOB(0x92fdba4)' fho='GLOB(0x92fdbcc)' fhe='' =========================================================================== Read STDOUT: STDOUT> [run#2] This should be STDOUT Read STDERR: STDOUT> this should be STDERR (run#2)... STDOUT> and so should this (run#2) run#2 --- fhi='GLOB(0x93811c0)' fho='GLOB(0x932bc60)' fhe='GLOB(0x92fdba4)' =========================================================================== Read STDOUT: STDOUT> [run#3] This should be STDOUT Read STDERR: STDOUT> this should be STDERR (run#3)... STDOUT> and so should this (run#3) run#3 --- fhi='GLOB(0x93811c0)' fho='GLOB(0x932bc60)' fhe='GLOB(0x92fdba4)' ===========================================================================