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

First I want to say I solved the problem with help from posts from tilly & maverick. Kudos to my fellow mongers for saving my butt again! However, I don't know why my original approach was failing so now I'm asking you. I needed to capture STDOUT in a web application. I was using IO::Scalar to do it via this code:
my $content; tie *STDOUT, 'IO::Scalar', \$content; do $file; untie *STDOUT; return $content;

What was happening is that I got the proper data back from the called code, but I couldn't print to STDOUT! If I printed $content to STDERR the error log showed the proper putput. It seems obvious to me now that STDOUT was somehow either getting closed or was not getting untied. Now I'm using

tie(*CAPTURE, 'IO::Scalar', \$content); select(CAPTURE); $| = 1; do $file; select(STDOUT); untie(*CAPTURE); return $content;
and it works 100% as expected. But I don't understand why the old approach did not work. This is a web app and the browser got nothing but some empty headers I believe Apache or CGI.pm was adding. Any thoughts?

Replies are listed 'Best First'.
Re: Capturing STDOUT
by rdfield (Priest) on Nov 05, 2002 at 09:41 UTC
    Apache/CGI works magic with STDOUT. You need something like:
    tie *LOCALFH, 'IO::Scalar', \$scalar; my $old_fh = select(LOCALFH); ...code that generates STDOUT... select $old_fh;
    Don't assume anything about the current default filehandle.

    rdfield

      That is what I ended up doing (without capturing the old default filehandle). However, what I'd like to know is what magic was going on that allowed me to tie STDOUT initially, but was preventing the untie from working. I figure out that the initial tie()'ing of STDOUT was successful, but the untie never was.