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

I have a follow-up question to one I asked very recently Suggested file name for CGI output, though basically unrelated (hence the new node). I have the following code to make gzipped ouput from a CGI.
use Compress::Zlib; if($out eq 'gz'){ binmode STDOUT; print("Content-type: application/x-gzip\n\n"); my $gz = gzopen(\*STDOUT, "wb") or die "Cannot open stdout: $gzerrno\n" ; foreach my $line (@lines){ $gz->gzwrite($line) or die "error writing: $gzerrno\n" ; } $gz->gzclose; }
With some help from the Monks, things work now as I want them as a stand-alone CGI. However, I'm now trying to do the same thing under mod_perl. I now see that STDOUT is tied in mod_perl, which prevents this techique from working there. What would be the best approach to get gzipped output from my script under mod_perl?

-a

Replies are listed 'Best First'.
Re: STDOUT and mod_perl
by philcrow (Priest) on Aug 29, 2006 at 14:17 UTC
    Since you probably need a handle, but you can't use STDOUT and don't want to use a real file, try Tie::Handle::ToMemory which allows you to work with a handle, but collect the data in a scalar. Once the compressed output is in the scalar, you can print it as normal so mod_perl will be happy.

    Phil

Re: STDOUT and mod_perl
by Anonymous Monk on Aug 29, 2006 at 13:39 UTC
      This is not exactly what I want, and I've already looked at these things. I am not looking to compress all the output in response to the request from the browser. I am looking to have my CGI give output as either 'gzipped' or as 'text' depending on an option selected by the user. If selected, I want the output to come as an file attachment.

      -a

        Look a little harder, CGI::Compress::Gzip works with mod_perl:
        Note that the Zlib library on which this code is ultimately based requires a fileno for the output filehandle. Where the output filehandle is faked (i.e. in mod_perl), we instead use in-memory compression. This is more wasteful of RAM, but it is the only solution I've found (and it is one shared by the Apache::* compression modules).