Subject: | [PATCH] Teach IO::CaptureOutput to be able to capture both STDERR and STDOUT into a single scalar |
Date: | Wed, 31 Jan 2007 16:38:08 +0100 |
To: | bug-IO-CaptureOutput [...] rt.cpan.org |
From: | Anton Berezin <tobez [...] tobez.org> |
The ability to do an equivalent of "> file 2>&1" for the in-code prints
comes in handy from time to time.
It looks like the easiest way to instruct IO::CaptureOutput::capture() to
handle this is to equate \$out and \$err. So that if one does
$| = 1;
capture {
print "1\n";
print STDERR "2\n";
print "3\n";
}, \$out, \$out;
the result will be "1\n2\n\3\n" in the $out scalar.
I hope this patch (or ay least this functionality) can be included in the
next version of the module.
Thanks!
--- CaptureOutput.pm Fri Mar 25 13:44:14 2005
+++ /usr/local/lib/perl5/site_perl/5.8.8/IO/CaptureOutput.pm Wed Jan 31 16:36:48 2007
@@ -14,9 +14,30 @@ sub capture (&@) {
$_ = \do { my $s; $s = ''} unless ref $_;
$$_ = '' unless defined($$_);
}
- my $capture_out = new IO::CaptureOutput::_proxy('STDOUT', $output);
- my $capture_err = new IO::CaptureOutput::_proxy('STDERR', $error);
- &$code();
+ my $capture_out;
+ my $capture_err;
+ my $olderr;
+ $capture_out = new IO::CaptureOutput::_proxy('STDOUT', $output);
+ if ($output == $error) {
+ open $olderr, ">&STDERR";
+ open STDERR, ">&STDOUT";
+ } else {
+ $capture_err = new IO::CaptureOutput::_proxy('STDERR', $error);
+ }
+ my ($r, @r);
+ unless (defined wantarray) {
+ &$code();
+ } elsif (wantarray) {
+ @r = &$code();
+ } else {
+ $r = &$code();
+ }
+ open STDERR, ">&", $olderr if $olderr;
+ if (wantarray) {
+ return @r;
+ } else {
+ return $r;
+ }
}
sub capture_exec {
Cheers,
\Anton.
--
We're going for 'working' here. 'clean' is for people with skills...
-- Flemming Jacobsen