rapide has asked for the wisdom of the Perl Monks concerning the following question:

I was looking for a solution no how the standard filehandle STDOUT can be redirected to an array.
The STDOUT must be within the same program. e.g.
Module::printData; my @data = STDOUT

I want to capture all the STDOUT information from the function "printData" without it printing to STDOUT.
Any suggestions?

Replies are listed 'Best First'.
Re: How to redirect STDOUT to an array (not executing program)
by cdarke (Prior) on Jan 18, 2009 at 11:55 UTC
    Depending on how far you want to go with using CPAN modules, it is fairly easy to redirect STDOUT to a scalar, see open:
    my $var; close STDOUT; open(STDOUT, '>', \$var) || die "Unable to open STDOUT: $!"; print "Hollow World\n"; print "And another\n"; close (STDOUT); my @data = split "\n", $var; local $" = '|'; print STDERR "<@data>\n";
    Beware that this does work for STDOUT in child processes.
      Great! Your example was exactly what I was looking for. Thank you
Re: How to redirect STDOUT to an array (not executing program)
by Corion (Patriarch) on Jan 18, 2009 at 11:44 UTC