paperazzo79
paperazzo79

Reputation: 355

Perl: parsing compressed files

I have a script that opens a big text-file and extracts data to create a report.

Question:

Is there a way to open the file in perl even if the file has been compressed with gzip?

Gunzip the file before opening would be to slow.

Example:

open(my $fh, "<", "input.txt.gz")

Upvotes: 0

Views: 253

Answers (1)

serenesat
serenesat

Reputation: 4709

IO::Uncompress::Unzip module can help you.

use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
unzip $input_filename_or_reference => $output_filename_or_reference [,OPTS] 
    or die "unzip failed: $UnzipError\n";

The functional interface needs Perl5.005 or better.

Or You can use CPAN module PerlIO::gzip:

use PerlIO::gzip;
open FOO, "<:gzip", "file.gz" or die $!;
print while <FOO>; # And it will be uncompressed...

binmode FOO, ":gzip(none)" # Starts reading deflate stream from here on

PerlIO::gzip provides a PerlIO layer that manipulates files in the format used by the gzip program. Compression and Decompression are implemented, but not together. If you attempt to open a file for reading and writing the open will fail.

Upvotes: 2

Related Questions