in reply to In a perl sub, how do I capture STDOUT, STDERR that comes from another perl sub?

In the open doc there is an example:

close STDOUT; open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";

You could combine that with local *STDOUT to limit that capturing to a scope:

#!/usr/bin/perl use warnings; use strict; sub writes_to_stdout { print "some information\n"; } sub captured { local *STDOUT; my $result; open STDOUT, '>', \$result; writes_to_stdout(); return $result; } my $val = captured(); print "No output yet\n"; print "But now: $val"; ## and this is what it writes: $ perl foo.pl No output yet But now: some information

Update: added complete example

Replies are listed 'Best First'.
Re^2: n a perl sub, how do I capture STDOUT, STDERR that comes from another perl sub?
by seank (Acolyte) on Aug 17, 2007 at 14:05 UTC
    Thank you very much to both of you, this exactly what I needed. Works like a charm.