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

Hello Monks, I want to make a copy of the contents of STDOUT to a variable without destroying them. I need to append more data to STDOUT and I will use that later. How do I do this? Thanks

Replies are listed 'Best First'.
Re: Copy contents of STDOUT
by almut (Canon) on Jan 25, 2010 at 17:40 UTC

    Another suggestion. Use PerlIO::Util's tee layer:

    #!/usr/bin/perl use strict; use warnings; use PerlIO::Util; *STDOUT->push_layer(tee => \my $capture_buf); print "hello world\n"; print STDERR "captured STDOUT: '$capture_buf'"; __END__ $ ./819527.pl hello world captured STDOUT: 'hello world '
Re: Copy contents of STDOUT
by kennethk (Abbot) on Jan 25, 2010 at 16:38 UTC
    I think your question could use a little more information, particularly what context is this to be implemented in. See How do I post a question effectively? and XY Problem. And what have you tried? Code is always appreciated.

    My best guess is that you are writing a wrapper script to intercept prints from other code. You can accomplish this by storing the STDOUT handle locally in the script and then redirecting the STDOUT handle to a variable. This is discussed in open. Something along the lines of:

    #!/usr/bin/perl use strict; use warnings; open my $oldout, '>&', STDOUT or die "Can't dup STDOUT: $!"; my $stream; close STDOUT; open STDOUT, '>', \$stream or die "Can't open STDOUT: $!"; print "Hello!\n"; $stream .= "This line is new!\n"; print $oldout $stream;

    where the above is assembled from code in open. Note that this should only be done at the highest level or undone in the same subroutine, as STDOUT is global and hence this could cause some weird action at a distance issues if you are incautious.

Re: Copy contents of STDOUT
by johngg (Canon) on Jan 25, 2010 at 17:32 UTC

    I'm not sure I understand from your question quite what you are trying to achieve but I wonder if IO::Tee might serve your needs.

    Cheers,

    JohnGG

Re: Copy contents of STDOUT
by jethro (Monsignor) on Jan 25, 2010 at 16:49 UTC

    You could override print with your own subroutine that would cache (i.e simply push into an array) everything that is printed

    Overriding so that you don't have to change anything else in your script is possible but might be difficult to get right (see http://search.cpan.org/~dapm/perl-5.10.1/pod/perlsub.pod#Overriding_Built-in_Functions____ )

    Easier is to change all STDOUT print statements to a simple call to your subroutine that does the caching and then prints