perlquestion
Mr. Muskrat
<p>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:<ol>
<li>Save a copy of STDERR.
<li>Redirect it to a temporary file.
<li>Run the process that only outputs on STDERR.
<li>Restore the original STDERR.
<li>Slurp the contents of the temporary file into a scalar.
</ol></p>
<p><readmore>
<p>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?
<p>
<code>
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 = <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?
</code>
</readmore></p>