Perl Language File I/O (reading and writing files) Reading and Writing gzip compressed files


Example

Writing a gzipped file

To write a gzipped file, use the module IO::Compress::Gzip and create a filehandle by creating a new instance of IO::Compress::Gzip for the desired output file:

use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

use IO::Compress::Gzip;

my $fh_out = IO::Compress::Gzip->new("hello.txt.gz");

print $fh_out "Hello World!\n";

close $fh_out;

use IO::Compress::Gzip;

Reading from a gzipped file

To read from a gzipped file, use the module IO::Uncompress::Gunzip and then create a filehandle by creating a new instance of IO::Uncompress::Gunzip for the input file:

#!/bin/env perl
use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

use IO::Uncompress::Gunzip;

my $fh_in = IO::Uncompress::Gunzip->new("hello.txt.gz");

my $line = readline $fh_in;

print $line;