http://qs321.pair.com?node_id=425459

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

Have you ever had a problem where you kinda knew what was going wrong ... I have that problem. I am using IO::Scalar and when I tie stdout like so:
my $str; my $io = tie *STDOUT, 'IO::Scalar', \$str; print_monks(); undef $io; untie *STDOUT; # $str now contains the output of the print_monks() function.
Everything works as expected, as long as the print_monks() function is in the same package. When I use a module that exports a function and then try to capture the output of that function in the same code as above, things go haywire. So this doesn't work:
use Some::Module qw(print_blah); my $str; my $io = tie *STDOUT, 'IO::Scalar', \$str; print_blah(); undef $io; untie *STDOUT; # print_blah() prints to stdout.
How can I get the output into $str in such a case? Thanks.

Replies are listed 'Best First'.
Re: tie stdout with IO::Scalar
by Mr. Muskrat (Canon) on Jan 27, 2005 at 05:40 UTC

    How about you show us an example were it doesn't capture the output? Here's one that shows it working.

    #!/usr/bin/perl use strict; use IO::Scalar; use Data::Dump qw(pp); use Data::Dumper::Simple; my $str; my $io = tie *STDERR, 'IO::Scalar', \$str; pp('monks'); undef $io; untie *STDERR; print Dumper($str); __DATA__ Z:\Perl>ioscalar.pl $str = '"monks" ';
        Thanks for the link.