Duh, very simple, just use TIE:
package IO::Redirect ; sub TIEHANDLE { my $class = shift ; my ($stdout , $globpath) = @_ ; my $prevstdout = \*{$globpath} ; my $this = { STDOUT => $stdout , PREVIO => $prevstdout , PREVIOPATH +=> $globpath } ; return bless($this , $class) ; } sub print { &PRINT ;} sub print_stdout { my $this = shift ; return 1 if $_[0] eq '' ; my $stdout = $this->{STDOUT} ; if ( ref($stdout) eq 'SCALAR' ) { $$stdout .= $_[0] ;} elsif ( ref($stdout) eq 'CODE' ) { &$stdout($this , $_[0]) ;} else { print $stdout $_[0] ;} return 1 ; } sub PRINT { my $this = shift ; $this->print_stdout( join("", (@_[0..$#_])) ) ; return 1 ; } sub PRINTF { &PRINT($_[0],sprintf($_[1],@_[2..$#_])) ;} sub CLOSE { my $this = shift ; untie *{ $this->{PREVIOPATH} } ; } sub UNTIE { my $this = shift ; *{ $this->{PREVIOPATH} } = $this->{PREVIO} ; } sub DESTROY { &CLOSE } ####### # END # ####### package main ; my $catcher ; tie(*{"main::STDOUT"} => 'IO::Redirect' , \$catcher , 'main::STDOUT' +) ; print "Hello World!\n" ; close( *main::STDOUT ) ; print "<<$catcher>>\n" ; exit;
By gmpassos

In reply to Re: Challenge: Capturing stdout from a function call. by Anonymous Monk
in thread Challenge: Capturing stdout from a function call. by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.