Perl: Compress/Decompress gzip Files

By Xah Lee. Date: . Last updated: .

Decompress gzip File

Use IO::Zlib module to compress/decompress gzip files.

# -*- coding: utf-8 -*-
# perl

# decompress a gzip file

use IO::Zlib;

$fh = new IO::Zlib;

if ($fh->open("file.gz", "rb")) {
    print <$fh>;
    $fh->close;
}

Compress gzip File

# -*- coding: utf-8 -*-
# perl

# gzip compress a file

$fh = IO::Zlib->new("file.gz", "wb9");
if (defined $fh) {
    print $fh "output_file.txt\n";
    $fh->close;
}

System Call to 「gzip」

You can also call the unix gzip with qx.

# -*- coding: utf-8 -*-
# perl

qx(gzip x.txt); # compress

qx(gzip -d x.txt.gz);   # decompress

2013-12-04 thanks to Robin Lee for tips.