http://qs321.pair.com?node_id=291299

Mr. Muskrat has asked for the wisdom of the Perl Monks concerning the following question:

I am attempting to redirect STDERR to a scalar. However, I'm using ActiveState Perl v5.6.1 (MSWin32-x86-multi-thread ) build 635. The only way that I found to work (so far anyway) is as follows:

  1. Save a copy of STDERR.
  2. Redirect it to a temporary file.
  3. Run the process that only outputs on STDERR.
  4. Restore the original STDERR.
  5. Slurp the contents of the temporary file into a scalar.

I have stripped down my code greatly to produce the following example script. Both &oldway and &newway work fine but which one is the best way of doing this?

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 STDE +RR open(STDERR, '>', $filename) || die "Can't redirect STDERR to the te +mp 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 te +mp 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 = <TXT>; # 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?