in reply to Challenge: Capturing stdout from a function call.

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

Replies are listed 'Best First'.
Re^2: Challenge: Capturing stdout from a function call.
by BUU (Prior) on Oct 22, 2004 at 23:00 UTC
    What a brilliant ide! It's too bad tie doesn't work. Maybe you should try testing your solution first?
      Tested on Perl 5.6.1 and it works. Depending on your Perl version you need to add the sub STORE {} to no get errors.

      Graciliano M. P.
      "Creativity is the expression of liberty".

        Yes, it works on the trivial example you used. It does not work with Perl.pm.