This is not quite the question I thought of in the
chatterbox. Use the IO::Scalar module from CPAN.
use IO::Scalar;
my $capture;
tie(*CAPTURE, 'IO::Scalar', \$capture);
select (CAPTURE);
And now the output goes into $capture. For details I
suggest reading up on tie.
BUT this approach has a big gotcha. Any and all
output that comes from Perl will be captured. Any and
all output that is done in C is unlikely to be. So for
instance any print you do goes to $capture. But if you
make a system call, not a chance.
The safer approach is to run a second process like this:
local *CAPTURE;
my $cmd = join " ", "perl", "script_name", @args);
open (CAPTURE, "$cmd |") or die "Cannot run command $cmd: $!";
And now the STDOUT of the second process can be read and
processed by the first. (On Unix you could actually do a
fork and have one process read from the other - the Cookbook
has an example.)
EDIT
If people are actually reading this I would like to point
out a minor detail. Note how I put the command to run
into a variable? I make it a point to always do that so that I
don't have to synchronize code to get the debugging
message to correctly report what failed. Even if it
means having a line like:
my $file = "foo.txt";
A small but significant detail I like to pay attention to. :-) |