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


in reply to Redirecting STDOUT from internal function with 5.6.1 restrictions

(Update: Wrapped the redirecting code into a convenient, reusable function.)

The following code shows one way of doing what you want in 5.6.1, all wrapped into a tidy function. It does use a temporary file, but the file is cleaned up automatically, and File::Temp uses a random file name to protect against certain kinds of file-based attacks.

use File::Temp qw( tempfile ); sub capture_output { my $target_fh = shift; my $temp_fh = tempfile(); my $temp_fd = fileno $temp_fh; local *SAVED; local *TARGET = $target_fh; open SAVED, ">&TARGET" or die "can't remember target"; open TARGET, ">&=$temp_fd" or die "can't redirect target"; my $saved_fh = *SAVED; return sub { seek $temp_fh, 0, 0 or die "can't seek"; # rewind my $captured_output = do { local $/; <$temp_fh> }; close $temp_fh or die "can't close temp file handle"; local (*SAVED, *TARGET) = ($saved_fh, $target_fh); open TARGET, ">&SAVED" or die "can't restore target"; close SAVED or die "can't close SAVED"; return $captured_output; } }
With this code in place, capturing output from any filehandle becomes easy:
print STDERR "before redirection\n"; my $recorder = capture_output(*STDERR); # start print STDERR "during redirection\n"; my $saved_output = $recorder->(); # stop print STDERR "after redirection\n"; print "Saved output = $saved_output";
The output is what you would expect (tested on Perl v5.6.1 built for i386-linux):
before redirection after redirection Saved output = during redirection

Sidebar: I don't know why you think a file-based solution is a hack. Unless you have a really good reason not to use a temp file, you'll probably find it to be the most practical, general-purpose solution.

Because you want to capture what is written to STDERR, you must preserve typical file-descriptor semantics. Using a temp file gives you this behavior for free.

Yes, you could try to use a tied filehandle, but the 5.6.1 perltie docs say that tied-filehandle support is only "partially implemented." More importantly, you'll be hosed if what you're testing ends up writing to the stderr file descriptor directly, bypassing your filehandle. This can easily happen if your code uses external libraries, which just about all code does implicitly via the standard C libraries that Perl links against.

Given that the temp-file solution will work in all situations and has the advantage of being drop-dead simple, my recommendation is to use it. Only if it proves inadequate in actual practice should you worry about more complicated solutions.

Cheers,
Tom