[LA.pm] calling gzip from within perl

Peter Benjamin pete at peterbenjamin.com
Wed Jun 29 00:21:20 PDT 2005


At 10:21 PM 6/28/2005, David Heayn wrote:
>At 12:36 PM +0800 6/29/05, Benjamin J. Tilly  wrote:
>>Why do you need to decompress them beforehand?
>>
>>   open(LOG, "gunzip $file |") or die "Cannot gunzip '$file': $!";
>>
>>Or you can avoid the implicit system command by using
>>Compress::Zlib.
>
>I tried the code above. It decompressed the files (and erased the 
>original) but perl didn't properly display them. In fact, it 
>displayed nothing but the html title and header.
>
>The changed code is below.
>
>if (param('action'))
>        {
>        print header;
>        my $year = param('year');
>        my $month = param('mo');
>        my $day = param('day');
>        my $seekLog = "access_log-$month.$day.$year";
>        my $fileLoc = "$logDir$seekLog.gz";
>        open(FILE, "gunzip $fileLoc |") or die "Cannot gunzip '$fileLoc': $!";
>        my @stuff = <FILE>;
>        close(FILE);
>
>
>Do i need to install compress:zlib to get this to work correctly?

Should not need to.  The gunzip that is invoked is the same as
system would do.  Does your script use STDIN?  If so, then
this method of re-using STDIN (the pipe after the filename in
the open) would cause problems.  They share the same /dev/*
file name that STDIN uses.  As it appears to be a CGI script
I suppose you will not be able to re-use STDIN using the |
inside the open.

BTW, as you know the $logDir why not use () to expand the file list?
And capture output from gunzip for errors or success?

chdir $logDir;
foreach my $fileLoc ( access_log-*.gz ) {
  my $stdout = `gunzip $fileLoc`;
  if ( $stdout =~ /(error1mesg|error2mesg)/ { 
     # handle error.
  } elsif (  $stdout =~ /successmesg/ ) {
    $fileLoc =~ /s\.gz//';
    open(FILE, "<$fileLoc") or die "Cannot open '$fileLoc': $!";
    my @stuff = <FILE>;
    close(FILE);
    ...more...
    unlink $fileLoc;
  } else {
     die "Cannot gunzip '$fileLoc':\n$stdout\n";
  }
}

Got to love perl shortcuts!





More information about the Losangeles-pm mailing list