in reply to How to capture STDOUT/STDERR of a function

STDERR and STDOUT can be localized, like any other global file handle, . That done you can call your function and output will go to the new handle. In perl 5.8,

my ($errors, $output); sub foo { print STDERR "Something to worry about\n"; } { open local(*STDERR), '>', \$errors; foo(); } warn "STDERR ought to be restored now"; $errors =~ s/Something/Nothing/; print $errors;
That takes 5.8+ because of the PerlIO trick of opening a file to memory by using a reference to a scalar in the filename slot. In pre-5.8 perls, you can use IO::Scalar or IO::Stringy for the same purpose.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: How to capture STDOUT/STDERR of a function
by Anonymous Monk on Aug 31, 2004 at 18:07 UTC
    Thanks, I didn't know about that. What I'm trying to do is to catch the output from Test::Harness, something like the following after your example:
    use strict; use Test::Harness; my $out; { open local(*STDOUT),'>',\$out; runtests(); } print $out;
    Somehow all results are still printed out to screen, not to the $out variable. I tried STDERR too, the same result. Thanks.

      Your use of the idiom is correct. The trouble is that Test::Harness does its own IO remapping.

      You could try running tests from the command line and redirecting output from there.

      After Compline,
      Zaxo

      Sorry, forgot to login for the above post.