Read and write gzip files in Perl
last modified November 25, 2026 Perl 5.44
Gzip compresses a stream of bytes. A file named events.log.gz
contains the compressed bytes of a log, not a directory of files like a ZIP
archive. Perl's IO::Compress::Gzip module writes gzip data and
IO::Uncompress::Gunzip reads it. Both modules ship with Perl, so
the examples do not need an external gzip command.
The examples create their own sample files. Run them in order from the same scratch directory, since the writing examples replace files with the same names.
Compress a string into a file
The gzip function takes a source and a destination. To compress
text already in memory, pass a reference to the scalar holding the text and
the name of the output file.
#!/usr/bin/perl
use warnings;
use v5.34.0;
use IO::Compress::Gzip qw(gzip $GzipError);
my $text = "INFO service started\nERROR disk full\n";
my $path = 'sample.log.gz';
gzip \$text => $path
or die "Cannot compress to $path: $GzipError\n";
say "Wrote $path";
The backslash in \$text tells the module to use the contents of
that scalar. An ordinary string argument would instead be treated as a file
name. The function finishes the whole compression operation in one call and
returns false on failure, with the reason in $GzipError.
$ perl make_sample_gzip.pl Wrote sample.log.gz
Decompress a small file into memory
The gunzip function reverses the operation. Here the source is
the file just created and the destination is a reference to a scalar. This is
convenient when the uncompressed text is small enough to fit in memory.
#!/usr/bin/perl
use warnings;
use v5.34.0;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
my $path = 'sample.log.gz';
my $text;
gunzip $path => \$text, Transparent => 0, Strict => 1
or die "Cannot decompress $path: $GunzipError\n";
print $text or die "Cannot write to standard output: $!\n";
With Transparent => 0, the module does not pass through plain
text as if it had been decompressed. Strict => 1 checks the gzip
trailer, the bytes at the end of the compressed stream that store a checksum
and the original size. If gunzip fails, the program reports
$GunzipError rather than printing the buffer.
$ perl show_sample_gzip.pl INFO service started ERROR disk full
Write a gzip log one line at a time
When records arrive one at a time, open an IO::Compress::Gzip
object and write each record as soon as it is available. The loop below
generates six records for the reader in the next section.
#!/usr/bin/perl
use warnings;
use v5.34.0;
use IO::Compress::Gzip qw($GzipError);
my $path = 'events.log.gz';
my $gz = IO::Compress::Gzip->new($path)
or die "Cannot open $path for compression: $GzipError\n";
for my $id (1 .. 6) {
my ($level, $state) = $id % 3 == 0
? ('ERROR', 'failed')
: ('INFO', 'done');
$gz->print("$level task=$id $state\n")
or die "Cannot write $path: $GzipError\n";
}
$gz->close or die "Cannot finish $path: $GzipError\n";
say "Wrote $path";
Every third record is an error. The program hands each line to the compressor
without assembling the complete log in memory or writing a plain
events.log file. Check close even if every call to
print succeeded: closing flushes pending compressed bytes and
writes the trailer, and either operation can fail.
$ perl write_event_gzip.pl Wrote events.log.gz
Stream a gzip log without extracting it
Open the compressed log with IO::Uncompress::Gunzip and call
getline in a loop. The program counts all lines and counts those
beginning with ERROR separately. It takes an optional file name
so we can reuse it to test a damaged copy.
#!/usr/bin/perl
use warnings;
use v5.34.0;
use IO::Uncompress::Gunzip qw($GunzipError);
my $path = $ARGV[0] // 'events.log.gz';
my $gz = IO::Uncompress::Gunzip->new(
$path, Transparent => 0, Strict => 1, MultiStream => 1,
) or die "Cannot open $path for decompression: $GunzipError\n";
my ($total, $errors) = (0, 0);
while (defined(my $line = $gz->getline)) {
++$total;
++$errors if $line =~ /\AERROR /;
}
die "Cannot read $path: $GunzipError\n" if $GunzipError ne '';
$gz->close or die "Cannot close $path: $GunzipError\n";
say "Events: $total";
say "Errors: $errors";
The program keeps counters and processes one line at a time, so it does not
need room for the complete uncompressed log or create an uncompressed file.
The module still buffers data internally, and a very long line can take a
lot of memory. MultiStream => 1 also reads successive gzip
streams if the file contains more than one, as when gzip files have been
joined end to end.
getline returns undef at the end of the input or on
a read or decompression error. Check $GunzipError immediately
after the loop and before closing. Otherwise a partial count could look like
a complete result.
$ perl summarize_event_gzip.pl Events: 6 Errors: 2
Detect a truncated gzip file
To test the reader, copy the six-record log and remove the last four bytes from the copy. The gzip trailer is eight bytes long, so this leaves the compressed records in place but damages the trailer.
#!/usr/bin/perl
use warnings;
use v5.34.0;
use File::Copy qw(copy);
my $source = 'events.log.gz';
my $path = 'truncated.log.gz';
copy($source, $path) or die "Cannot copy $source to $path: $!\n";
my $size = -s $path;
die "$path is too short to contain a gzip trailer\n"
unless defined($size) && $size >= 8;
truncate($path, $size - 4) or die "Cannot truncate $path: $!\n";
say "Wrote $path";
The original log is unchanged. When the summary program reaches the damaged trailer, strict mode reports that it is too short. The program exits with an error instead of writing a summary. Checking only whether the file opens would not catch this problem.
$ perl make_truncated_gzip.pl Wrote truncated.log.gz $ perl summarize_event_gzip.pl truncated.log.gz Cannot read truncated.log.gz: Trailer Error: trailer truncated. Expected 8 bytes, got 4
Best practices
When decompressing to a file, write to a temporary path first and replace the destination only after decompression and closing succeed. A damaged archive can produce some valid output before the reader notices the error at the end.
Source
IO::Compress::Gzip and IO::Uncompress::Gunzip document the functions, streaming objects and options used here. The gzip format specification describes the gzip header and trailer.
In this article we compressed and decompressed a small log, wrote a gzip log incrementally, and read it line by line without extracting a copy. We also checked that a truncated file fails instead of producing a partial summary. See also Perl read file, Perl write file and Perl binary files.
Author
List all Perl tutorials.