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

Hey, monks!

I'm using an internal module which prints standardized CSS settings to STDOUT. Is there a way I can redirect this to a scalar? Yeah, it would make sense to just rewrite the module, but this is standardized, & I need it in a different manner than what was anticipated.

Thanks!

Replies are listed 'Best First'.
Re: redirecting STDOUT output to variable?
by ikegami (Patriarch) on Jul 27, 2009 at 19:38 UTC
    The following might be sufficient:
    { my $captured_stdout = ''; local *STDOUT; open(STDOUT, '>', \$captured_stdout) or die $!; ... }
Re: redirecting STDOUT output to variable?
by Your Mother (Archbishop) on Jul 27, 2009 at 19:13 UTC

    IO::CaptureOutput will do and is easier, to me, than select magic on the various handles. You are right though that it would probably make more sense to rewrite the module. Don't dig in with shims to inappropriate code if you can take a little time to fix the code to behave itself and leave the disposition of output up to the caller.

Re: redirecting STDOUT output to variable?
by Marshall (Canon) on Jul 27, 2009 at 21:17 UTC
    The first question is how to open a scalar for I/O write?
    #!/usr/bin/perl -w use strict; my $output; open (OUT, ">", \$output) or die "can't open scalar for out"; print OUT "this is some line\n"; print OUT "this is another line\n"; print "printing the output variable:\n"; print $output; __END__ OUTPUT..... printing the output variable: this is some line this is another line
    I think you can also open STDOUT like above. Of course then you have to do something else to test rather just print!

    Update:Saw Ikegami's code after I posted. That looks great also. I didn't quite understand the context of why you want to do this?