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

Hello,

Is is possible to use the zless utility and Perl's open function to read a gzipped file?

I tried using open and piping to zless but that did not work. Ultimately, I would like to read a gzipped file line by line with a while loop without unzipping it such as:

open(FILE, '<', $filename) #somehow using zless or other? while <FILE> { ...do action on each line... }

Replies are listed 'Best First'.
Re: perl OPEN function and zless
by davido (Cardinal) on Jul 14, 2011 at 21:17 UTC

    CPAN: Perl's killer app: PerlIO::via::gzip

    I don't know how robust this is, but it worked on a simple test script I just tried myself.

    use strict; use warnings; use autodie; use PerlIO::via::gzip; my $filename = 'example.txt.gz'; open my $fh, "<:via(gzip)", $filename; while ( <$fh> ) { print $. . $_; }

    I think that's what you seem to be looking for. You could always just open a pipe from the shell instead though.


    Dave

      Thanks, I will look at that but I have used the pipe function from the shell instead for now
Re: perl OPEN function and zless
by betterworld (Curate) on Jul 14, 2011 at 21:02 UTC

    Why would you want to read from zless? It's a pager, which is designed to scroll through a gzipped file (on a terminal). Better choices are 'gunzip' or 'zcat' (maybe look at the man pages).

    To use these tools with "open", you need to use "-|" rather than "<". perldoc -f open will tell you more about it.

    Searching CPAN for gzip might also help. IO::Uncompress::Gunzip is installed with perl by default.

      Thanks,
      I used this to get it to work:
      open(FILE, '-|', "gunzip -c $filename"); while (FILE) { ..do action.. }