title: What is the best way to gunzip files with Perl?
body: <p>Is there a faster solution than my actual 'zcat' solution to gunzip files with Perl?</p>
  
  <p>A little benchmark:</p>
  
  <pre><code>#!/usr/bin/perl
  
  use strict;
  use warnings;
  use Benchmark qw(cmpthese timethese);
  use IO::Uncompress::Gunzip qw(gunzip);
  
  my $re = qr/test/;
  
  my $bench = timethese($ARGV[1], {
  
    zcat =&gt; sub {
      if (defined open(my $FILE, "-|", "zcat " . $ARGV[0]))
      {
        while (&lt;$FILE&gt;)
        {
          print $_  if ($_ =~ $re);
        }
        close($FILE);
      }
    },
  
    io_gunzip =&gt; sub {
      my $z = new IO::Uncompress::Gunzip $ARGV[0];
      while (&lt;$z&gt;)
      {
        print $_  if ($_ =~ $re);
      }
    },
  
    io_gunzip_getline =&gt; sub {
      my $z = new IO::Uncompress::Gunzip $ARGV[0];
      while (my $line = $z-&gt;getline())
      {
        print $line if ($line =~ $re);
      }
    },
  
  } );
  
  cmpthese $bench;
  
  1;
  </code></pre>
  
  <p>give me these results:</p>
  
  <pre><code># zcat test.gz|wc -l
  566
  # zcat test2.gz|wc -l
  60459
  
  # ./zip_test.pl test.gz 500
  Benchmark: timing 500 iterations of io_gunzip, io_gunzip_getline, zcat...
   io_gunzip:  4 wallclock secs ( 3.01 usr +  0.01 sys =  3.02 CPU) @ 165.56/s (n=500)
  io_gunzip_getline:  3 wallclock secs ( 2.58 usr +  0.03 sys =  2.61 CPU) @ 191.57/s (n=500)
        zcat:  2 wallclock secs ( 0.20 usr  0.34 sys +  0.55 cusr  1.10 csys =  2.19 CPU) @ 228.31/s (n=500)
                     Rate         io_gunzip io_gunzip_getline              zcat
  io_gunzip         166/s                --              -14%              -27%
  io_gunzip_getline 192/s               16%                --              -16%
  zcat              228/s               38%               19%                --
  
  # ./zip_test.pl test2.gz 50
  Benchmark: timing 50 iterations of io_gunzip, io_gunzip_getline, zcat...
   io_gunzip: 31 wallclock secs (29.67 usr +  0.11 sys = 29.78 CPU) @  1.68/s (n=50)
  io_gunzip_getline: 26 wallclock secs (24.86 usr +  0.04 sys = 24.90 CPU) @  2.01/s (n=50)
        zcat:  5 wallclock secs ( 2.42 usr  0.19 sys +  1.19 cusr  0.27 csys =  4.07 CPU) @ 12.29/s (n=50)
                      Rate         io_gunzip io_gunzip_getline              zcat
  io_gunzip         1.68/s                --              -16%              -86%
  io_gunzip_getline 2.01/s               20%                --              -84%
  zcat              12.3/s              632%              512%                --
  </code></pre>
  
  <p>And I also don't understand why "<code>while (&lt;$z&gt;)</code>" is slower than "<code>while (my $line = $z-&gt;getline())</code>"...</p>