use File::Temp 'tempfile'; print "Trying oldway...\n"; my $oldway = oldway(); # should not display anything print "Finished with oldway.\n"; print $oldway; print "Testing STDERR...\n"; print STDERR "(STDERR) can you hear me?\n"; print "Trying newway...\n"; my $newway = newway(); # should not display anything print "Finished with newway.\n"; print $newway; print "Testing STDERR...\n"; print STDERR "(STDERR) can you hear me now?\n"; sub oldway { my ($fh, $filename) = tempfile(UNLINK => 1); open(OLDERR, ">&STDERR") || die "Can't save STDERR, $!"; # save STDERR open(STDERR, '>', $filename) || die "Can't redirect STDERR to the temp file, $!"; select(STDERR); $| = 1; print STDERR "oldway says 'hi'\n"; open(STDERR, ">&OLDERR"); # restore the original STDERR select(STDOUT); my $oldway = slurp_file($filename); return $oldway; } sub newway { my ($fh, $filename) = tempfile(UNLINK => 1); *oldfh = select STDERR; # save STDERR open(STDERR, '>', $filename) || die "Can't redirect STDERR to the temp file, $!"; select(STDERR); $| = 1; print STDERR "newway says 'hi'\n"; open(STDERR, ">&oldfh"); # restore STDERR select(STDOUT); my $newway = slurp_file($filename); return $newway; } sub slurp_file { my $filename = shift; my $slurp; open(TXT, '<', $filename) || die "Can't read the file: $filename, $!"; { local $/ = undef; $slurp = ; # slurp! } close(TXT); return $slurp; } __DATA__ Trying oldway... Finished with oldway. oldway says 'hi' Testing STDERR... (STDERR) can you hear me? Trying newway... Finished with newway. newway says 'hi' Testing STDERR... (STDERR) can you hear me now?