IO::Compress::Zip(3pm)
bestie, welcome to the IO::Compress::Zip(3pm) page β this is the Perl girlie who writes zip files and buffers, and she is absolutely serving π
β¨ NAME β¨
IO::Compress::Zip β write zip files/buffers. like, that's literally the whole name and the whole job π
πΈ SYNOPSIS πΈ
okay so here's the exact spellbook, copied character-for-character so you don't have to squint at manpage font π
use IO::Compress::Zip qw(zip $ZipError) ;
my $status = zip $input => $output [,OPTS]
or die "zip failed: $ZipError\n";
my $z = IO::Compress::Zip->new( $output [,OPTS] )
or die "zip failed: $ZipError\n";
$z->print($string);
$z->printf($format, $string);
$z->write($string);
$z->syswrite($string [, $length, $offset]);
$z->flush();
$z->tell();
$z->eof();
$z->seek($position, $whence);
$z->binmode();
$z->fileno();
$z->opened();
$z->autoflush();
$z->input_line_number();
$z->newStream( [OPTS] );
$z->deflateParams();
$z->close() ;
$ZipError ;
# IO::File mode
print $z $string;
printf $z $format, $string;
tell $z
eof $z
seek $z, $position, $whence
binmode $z
fileno $z
close $z ;
like, yes, that's a lot of methods β she's thorough and we respect it π
π¦ DESCRIPTION π¦
so this module gives you a Perl interface that lets you write zip compressed data to files or buffers. that's the vibe β¨
the main character purpose? providing streaming write access to zip files and buffers. lowkey iconic β you're writing as you go, not doing the whole "make it all first" thing π
at present, these compression methods are supported by IO::Compress::Zip, and yes we're listing every single one:
Store (0)β no compression, just vibes π«ΆDeflate (8)β the classic deflate moment β¨Bzip2 (12)β to write Bzip2 content, the moduleIO::Uncompress::Bunzip2must be installed πLzma (14)β to write LZMA content, the moduleIO::Uncompress::UnLzmamust be installed πΈZstandard (93)β to write Zstandard content, the moduleIO::Compress::Zstdmust be installed π¦Xz (95)β to write Xz content, the moduleIO::Uncompress::UnXzmust be installed π
and when you wanna read zip files/buffers instead of writing them, the companion module is IO::Uncompress::Unzip β go say hi π«Ά
π Functional Interface π
ok so there's a top-level function called zip that handles the whole "one-shot" compression thing between buffers and/or files. if you want finer control over the compression process tho, go peek at the "OO Interface" section β that's where the real customization lives.
use IO::Compress::Zip qw(zip $ZipError) ;
zip $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "zip failed: $ZipError\n";
fr fr, the functional interface needs Perl5.005 or better. ancient. she runs anyway π
πΈ zip $input_filename_or_reference => $output_filename_or_reference [, OPTS]
zip expects at least two parameters β $input_filename_or_reference and $output_filename_or_reference β and zero or more optional ones (those live down in "Optional Parameters", keep scrolling bestie).
π The $input_filename_or_reference parameter
This parameter defines where the uncompressed data is coming from. It can take one of these forms:
- A filename β if it's a simple scalar, it's assumed to be a filename. The file gets opened for reading and the input data is read from it.
- A filehandle β if it's a filehandle, the input data is read from it. the string
'-'can be used as an alias for standard input, iconic. - A scalar reference β if it's a scalar reference, the input data is read from
$$input_filename_or_reference. - An array reference β if it's an array reference, every element in the array must be a filename. The input data is read from each file in turn. and heads up: the complete array will be walked to make sure it only contains valid filenames before any data is compressed. safety first β¨
- An Input FileGlob string β if it's a string delimited by the characters
<and>,zipwill assume it's an input fileglob string. The input is the list of files that match the fileglob. See File::GlobMapper for more details.
If $input_filename_or_reference is any other type, undef gets returned. no cap.
Also (and this is lowkey the best part), if $input_filename_or_reference corresponds to a filename from the filesystem, a bunch of zip file header fields get populated by default using these attributes from the input file:
- the full filename contained in
$input_filename_or_reference - the file protection attributes
- the UID/GID for the file
- the file timestamps
If you don't want those defaults, they can be overridden by explicitly setting one or more of the "Name", "Time", "TextFlag", "ExtAttr", "exUnixN" and "exTime" options, or by setting the "Minimal" parameter. your archive, your rules π
π¦ The $output_filename_or_reference parameter
This one controls where the compressed data ends up. It can take one of these forms:
- A filename β if it's a simple scalar, it's assumed to be a filename. The file gets opened for writing and the compressed data is written to it.
- A filehandle β if it's a filehandle, the compressed data is written to it. the string
'-'can be used as an alias for standard output. - A scalar reference β if it's a scalar reference, the compressed data is stored in
$$output_filename_or_reference. - An Array Reference β if it's an array reference, the compressed data gets pushed onto the array.
- An Output FileGlob β if it's a string delimited by the characters
<and>,zipwill assume it's an output fileglob string. The output is the list of files that match the fileglob. When$output_filename_or_referenceis a fileglob string,$input_filename_or_referencemust also be a fileglob string β anything else is an error, bestie, don't test it. See File::GlobMapper for more details.
If $output_filename_or_reference is any other type, undef gets returned.
π«Ά Notes
When $input_filename_or_reference maps to multiple files/buffers and $output_filename_or_reference is a single file/buffer, the input files/buffers will each be stored in $output_filename_or_reference as a distinct entry. like a lil zip full of friends π
β¨ Optional Parameters β¨
The optional parameters for the one-shot zip function are (for the most part) identical to the ones used with the OO interface over in "Constructor Options". The exceptions are listed below:
"AutoClose => 0|1"β this one applies to any input or output data streams tozipthat are filehandles. IfAutoCloseis specified and the value is true, all input and/or output filehandles get closed onceziphas completed. Defaults to0."BinModeIn => 0|1"β this option is now a no-op. All files are read in binmode. that's it, that's the whole option π"Append => 0|1"β the behaviour of this one depends on the type of output data stream:- A Buffer β if
Appendis enabled, all compressed data is appended to the end of the output buffer. Otherwise the output buffer gets cleared before any compressed data is written to it. - A Filename β if
Appendis enabled, the file is opened in append mode. Otherwise the contents of the file, if any, get truncated before any compressed data is written to it. - A Filehandle β if
Appendis enabled, the filehandle is positioned to the end of the file via a call toseekbefore any compressed data is written to it. Otherwise the file pointer is not moved.
- A Buffer β if
When Append is specified and set to true, it appends all compressed data to the output data stream. So when the output is a filehandle it carries out a seek to the eof before writing any compressed data. If the output is a filename, it gets opened for appending. If the output is a buffer, all compressed data gets appended to the existing buffer.
Conversely, when Append is not specified β or it's present and set to false β it operates like this: when the output is a filename, it truncates the contents of the file before writing any compressed data. If the output is a filehandle, its position is not changed. If the output is a buffer, it gets wiped before any compressed data is output.
Defaults to 0.
π Oneshot Examples π
Here are a few examples showing off what the module can do, bestie. vibe check passed β
π Streaming
This very simple command line example demonstrates the streaming capabilities of the module. The code reads data from STDIN, compresses it, and writes the compressed data to STDOUT.
$ echo hello world | perl -MIO::Compress::Zip=zip -e 'zip \*STDIN => \*STDOUT' >output.zip
The special filename "-" can be used as a standin for both \*STDIN and \*STDOUT, so the above can be rewritten as
$ echo hello world | perl -MIO::Compress::Zip=zip -e 'zip "-" => "-"' >output.zip
One problem with creating a zip archive directly from STDIN can be demonstrated by looking at the contents of the zip file, output.zip, that we have just created.
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:21
--------- -------
12 1 file
The archive member (filename) used is the empty string. awk.
If that doesn't suit your needs, you can explicitly set the filename used in the zip archive by specifying the Name option, like so
echo hello world | perl -MIO::Compress::Zip=zip -e 'zip "-" => "-", Name => "hello.txt"' >output.zip
Now the contents of the zip file looks like this
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:22 hello.txt
--------- -------
12 1 file
much better, we ate π
πΈ Compressing a file from the filesystem
To read the contents of the file "file1.txt" and write the compressed data to the file "file1.txt.zip".
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my $input = "file1.txt";
zip $input => "$input.zip"
or die "zip failed: $ZipError\n";
π¦ Reading from a Filehandle and writing to an in-memory buffer
To read from an existing Perl filehandle, $input, and write the compressed data to a buffer, $buffer.
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt" )
or die "Cannot open 'file1.txt': $!\n" ;
my $buffer ;
zip $input => \$buffer
or die "zip failed: $ZipError\n";
π§ Compressing multiple files
To create a zip file, "output.zip", that contains the compressed contents of the files "alpha.txt" and "beta.txt"
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
zip [ 'alpha.txt', 'beta.txt' ] => 'output.zip'
or die "zip failed: $ZipError\n";
Alternatively, rather than having to explicitly name each of the files that you want to compress, you could use a fileglob to select all the "txt" files in the current directory, as follows
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my @files = <*.txt>;
zip \@files => 'output.zip'
or die "zip failed: $ZipError\n";
or more succinctly
zip [ <*.txt> ] => 'output.zip'
or die "zip failed: $ZipError\n";
π OO Interface π
π Constructor
The format of the constructor for IO::Compress::Zip is shown below
my $z = IO::Compress::Zip->new( $output [,OPTS] )
or die "IO::Compress::Zip failed: $ZipError\n";
The constructor takes one mandatory parameter, $output (defined below), and zero or more OPTS, defined in "Constructor Options".
It returns an IO::Compress::Zip object on success and undef on failure. The variable $ZipError will contain an error message on failure. π when it fails, it fails loud.
Okay so if you're running Perl 5.005 or better, the object $z you get back from IO::Compress::Zip can be used exactly like an IO::File filehandle. That means all the normal output file operations work with $z, no cap π
. So to write to a compressed file/buffer, either of these forms is valid:
$z->print("hello world\n");
print $z "hello world\n";
Below is a simple example of using the OO interface to create an output file myfile.zip and write some data to it:
my $filename = "myfile.zip";
my $z = IO::Compress::Zip->new($filename)
or die "IO::Compress::Zip failed: $ZipError\n";
$z->print("abcde");
$z->close();
See the "Examples" for more. β¨
The mandatory parameter $output controls where the compressed data goes. This parameter can take one of these forms:
A filename
If the $output parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the compressed data will be written to it.
A filehandle
If the $output parameter is a filehandle, the compressed data will be written to it. The string - can be used as an alias for standard output.
A scalar reference
If $output is a scalar reference, the compressed data will be stored in $$output.
If the $output parameter is any other type, "IO::Compress::Zip"::new will return undef.
π Constructor Options π
OPTS is any combination of zero or more of these options:
AutoClose => 0|1β This option is only valid when the$outputparameter is a filehandle. If specified and the value is true, it will result in the$outputbeing closed once either theclosemethod is called or theIO::Compress::Zipobject is destroyed.
This parameter defaults to 0.
Append => 0|1β Opens$outputin append mode.
The behaviour of this option is dependent on the type of $output.
- A Buffer β If
$outputis a buffer andAppendis enabled, all compressed data will be append to the end of$output. Otherwise$outputwill be cleared before any data is written to it. - A Filename β If
$outputis a filename andAppendis enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any compressed data is written to it. - A Filehandle β If
$outputis a filehandle, the file pointer will be positioned to the end of the file via a call toseekbefore any compressed data is written to it. Otherwise the file pointer will not be moved.
This parameter defaults to 0.
π File Naming Options π
A quick bit of zip file terminology β a zip archive consists of one or more archive members, where each member has an associated filename, known as the archive member name.
The options listed in this section control how the archive member name (or filename) is stored the zip archive.
Name => $stringβ This option is used to explicitly set the archive member name in the zip archive to$string. Most of the time you don't need to make use of this option. By default when adding a filename to the zip archive, the archive member name will match the filename.
You should only need to use this option if you want the archive member name to be different from the uncompressed filename or when the input is a filehandle or a buffer.
The default behaviour for what archive member name is used when the Name option is not specified depends on the form of the $input parameter:
- If the
$inputparameter is a filename, the value of$inputwill be used for the archive member name. - If the
$inputparameter is not a filename, the archive member name will be an empty string.
Note that both the CanonicalName and FilterName options can modify the value used for the archive member name.
Also note that you should set the Efs option to true if you are working with UTF8 filenames.
CanonicalName => 0|1β This option controls whether the archive member name is normalized into Unix format before being written to the zip file.
It is recommended that you enable this option unless you really need to create a non-standard Zip file.
This is what APPNOTE.TXT has to say on what should be stored in the zip filename header field:
The name of the file, with optional relative path. The path stored should not contain a drive or device letter, or a leading slash. All slashes should be forward slashes '/' as opposed to backwards slashes '' for compatibility with Amiga and UNIX file systems etc.
This option defaults to false.
FilterName => sub { ... }β This option allow the archive member name to be modified before it is written to the zip file.
This option takes a parameter that must be a reference to a sub. On entry to the sub the $_ variable will contain the name to be filtered. If no filename is available $_ will contain an empty string.
The value of $_ when the sub returns will be used as the archive member name.
Note that if CanonicalName is enabled, a normalized filename will be passed to the sub.
If you use FilterName to modify the filename, it is your responsibility to keep the filename in Unix format.
Although this option can be used with the OO interface, it is of most use with the one-shot interface. For example, the code below shows how FilterName can be used to remove the path component from a series of filenames before they are stored in $zipfile.
sub compressTxtFiles
{
my $zipfile = shift ;
my $dir = shift ;
zip [ <$dir/*.txt> ] => $zipfile,
FilterName => sub { s[^$dir/][] } ;
}
Efs => 0|1β This option controls setting of the "Language Encoding Flag" (EFS) in the zip archive. When set, the filename and comment fields for the zip archive MUST be valid UTF-8.
If the string used for the filename and/or comment is not valid UTF-8 when this option is true, the script will die with a "wide character" error.
Heads up, bestie: this option only works with Perl 5.8.4 or better.
This option defaults to false.
πΈ Overall Zip Archive Structure πΈ
Minimal => 1|0β If specified, this option will disable the creation of all extra fields in the zip local and central headers. So theexTime,exUnix2,exUnixN,ExtraFieldLocalandExtraFieldCentraloptions will be ignored.
This parameter defaults to 0.
Stream => 0|1β This option controls whether the zip file/buffer output is created in streaming mode.
Note that when outputting to a file with streaming mode disabled (Stream is 0), the output file must be seekable.
The default is 1.
Zip64 => 0|1β Create a Zip64 zip file/buffer. This option is used if you want to store files larger than 4 Gig or store more than 64K files in a single zip archive.
Zip64 will be automatically set, as needed, if working with the one-shot interface when the input is either a filename or a scalar reference.
If you intend to manipulate the Zip64 zip files created with this module using an external zip/unzip, make sure that it supports Zip64.
In particular, if you are using Info-Zip you need to have zip version 3.x or better to update a Zip64 archive and unzip version 6.x to read a zip64 archive.
The default is 0.
π₯ Deflate Compression Options π₯
-Levelβ Defines the compression level used by zlib. The value should either be a number between 0 and 9 (0 means no compression and 9 is maximum compression), or one of the symbolic constants defined below.
Z_NO_COMPRESSION
Z_BEST_SPEED
Z_BEST_COMPRESSION
Z_DEFAULT_COMPRESSION
The default is Z_DEFAULT_COMPRESSION.
Note, these constants are not imported by IO::Compress::Zip by default.
use IO::Compress::Zip qw(:strategy);
use IO::Compress::Zip qw(:constants);
use IO::Compress::Zip qw(:all);
-Strategyβ Defines the strategy used to tune the compression. Use one of the symbolic constants defined below.
Z_FILTERED
Z_HUFFMAN_ONLY
Z_RLE
Z_FIXED
Z_DEFAULT_STRATEGY
The default is Z_DEFAULT_STRATEGY.
π¦ Bzip2 Compression Options π¦
BlockSize100K => numberβ Specify the number of 100K blocks bzip2 uses during compression.
Valid values are from 1 to 9, where 9 is best compression.
This option is only valid if the Method is ZIP_CM_BZIP2. It is ignored otherwise.
The default is 1.
WorkFactor => numberβ Specifies how much effort bzip2 should take before resorting to a slower fallback compression algorithm.
Valid values range from 0 to 250, where 0 means use the default value 30.
This option is only valid if the Method is ZIP_CM_BZIP2. It is ignored otherwise.
The default is 0.
π Lzma and Xz Compression Options π
Preset => numberβ Used to choose the LZMA compression preset.
Valid values are 0-9 and LZMA_PRESET_DEFAULT.
0 is the fastest compression with the lowest memory usage and the lowest compression.
9 is the slowest compression with the highest memory usage but with the best compression.
This option is only valid if the Method is ZIP_CM_LZMA. It is ignored otherwise.
Defaults to LZMA_PRESET_DEFAULT (6).
Extreme => 0|1β Makes LZMA compression a lot slower, but a small compression gain.
This option is only valid if the Method is ZIP_CM_LZMA. It is ignored otherwise.
Defaults to 0.
β Other Options β
Time => $numberβ Sets the last modified time field in the zip header to$number.
This field defaults to the time the IO::Compress::Zip object was created if this option is not specified and the $input parameter is not a filename.
ExtAttr => $attrβ This option controls the "external file attributes" field in the central header of the zip file. This is a 4 byte field.
okay so real quick on the default β if you're running a Unix derivative, this value defaults to
0100644 << 16
which should let you read/write any files that get extracted from the zip file/buffer π
For every other system it defaults to 0.
exTime => [$atime, $mtime, $ctime]β bestie this one wants an array reference with exactly three elements:$atime,$mtimeand$ctime. Those are the last access time, last modification time and creation time, respectively. It takes those values and sets the extended timestamp field (ID isUT) in the local zip header using all three of$atime,$mtime,$ctime. On top of that it sets the extended timestamp field in the central zip header using$mtime. If any of the three values isundef, that time just doesn't get used, periodt. So say you only wanna set the$mtime, you'd do:
exTime => [undef, $mtime, undef]
Heads up: if the Minimal option is true, this option gets ignored entirely. And by default, no extended time field is created at all.
exUnix2 => [$uid, $gid]β expects an array reference with exactly two elements:$uidand$gid, aka the numeric User ID (UID) and Group ID (GID) of whoever owns the files. WhenexUnix2is present it triggers creation of a Unix2 extra field (ID isUx) in the local zip header, populated with$uidand$gid. An empty Unix2 extra field also gets created in the central zip header π«Ά
Note: the UID & GID are stored as 16-bit integers in theUxfield. If your UID or GID are 32-bit, useexUnixNinstead, iykyk.
If Minimal is true, this option is ignored. By default no Unix2 extra field is created.
exUnixN => [$uid, $gid]β same deal, array reference with exactly two elements:$uidand$gid, the numeric User ID (UID) and Group ID (GID) of the file owners. WhenexUnixNis present it triggers creation of a UnixN extra field (ID isuxβ lowercase bestie, don't mix it up with the Unix2 one π) in both the local and central zip headers, populated with$uidand$gid. Here the UID & GID are stored as 32-bit integers β¨
If Minimal is true, this option is ignored. By default no UnixN extra field is created.
Comment => $commentβ stores the contents of$commentin the Central File Header of the zip file. Wanna store a UTF8 comment? Set theEfsoption to true. By default, no comment field is written to the zip file.ZipComment => $commentβ stores the contents of$commentin the End of Central Directory record of the zip file. By default, no comment field is written to the zip file.Method => $methodβ controls which compression method gets used. rn the supported methods are: Store (no compression at all), Deflate, Bzip2, Zstd, Xz and Lzma π₯ The symbolsZIP_CM_STORE,ZIP_CM_DEFLATE,ZIP_CM_BZIP2,ZIP_CM_ZSTD,ZIP_CM_XZandZIP_CM_LZMAare what you use to pick the method.
These constants are not imported by IO::Compress::Zip by default, so you gotta ask nicely:
use IO::Compress::Zip qw(:zip_method);
use IO::Compress::Zip qw(:constants);
use IO::Compress::Zip qw(:all);
Important: to create Bzip2 content, the moduleIO::Compress::Bzip2must be installed. Attempt to create Bzip2 content without it and you get a fatal error, no cap. Same warning for Lzma βIO::Compress::Lzmamust be installed, otherwise fatal error. Same for Xz βIO::Compress::Xzmust be installed, otherwise fatal error. And same for Zstd βIO::Compress::Zstdmust be installed, otherwise fatal error π
The default method is ZIP_CM_DEFLATE.
TextFlag => 0|1β this parameter controls the setting of a bit in the zip central header. It's used to signal that the data stored in the zip file/buffer is probably text. In one-shot mode this flag gets set to true if the Perl-Toperator thinks the file contains text. The default is0.ExtraFieldLocal => $dataExtraFieldCentral => $dataβExtraFieldLocalstores additional metadata in the local header for the zip file/buffer, andExtraFieldCentraldoes the exact same thing for the matching central header π
An extra field is made of zero or more subfields. Each subfield is a two byte header followed by the subfield data.
You can hand over the list of subfields in any of these formats:
ExtraFieldLocal => [$id1, $data1,
$id2, $data2,
...
]
ExtraFieldLocal => [ [$id1 => $data1],
[$id2 => $data2],
...
]
ExtraFieldLocal => { $id1 => $data1,
$id2 => $data2,
...
}
where $id1, $id2 are two byte subfield ID's.
ngl, small caveat: if you use the hash syntax you have zero control over the order the ExtraSubFields are stored in, plus you can't have SubFields with duplicate IDs. That's just how it is π
Alternatively you can supply the list of subfields as a scalar, like:
ExtraField => $rawdata
In that case IO::Compress::Zip will check that $rawdata consists of zero or more conformant sub-fields.
Iconic examples of extra fields: the Extended Time field (ID UT), set via the exTime option, and the Unix2 extra field (ID Ux), set via the exUnix2 option.
If Minimal is true, this option is ignored.
The maximum size of an extra field is 65535 bytes β
Strict => 0|1β this is a placeholder option. That's it. That's the whole thing π
π Examples π
β¨ Streaming β¨
This very simple command line example shows off the streaming capabilities of the module. The code reads data from STDIN or all the files given on the commandline, compresses it, and writes the compressed data to STDOUT:
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my $z = IO::Compress::Zip->new("-", Stream => 1)
or die "IO::Compress::Zip failed: $ZipError\n";
while (<>) {
$z->print("abcde");
}
$z->close();
Note the use of "-" to mean "STDOUT". Or you can use "\*STDOUT" if that's more your vibe.
One problem with creating a zip archive directly from STDIN is demonstrable if you peek at the contents of the zip file, output.zip, that we just created (assuming you redirected it to a file called output.zip):
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:21
--------- -------
12 1 file
The archive member (filename) used is the empty string. Yeah. Nothing. Void. π
If that doesn't suit your needs, you can explicitly set the filename used in the zip archive by specifying the Name option, like so:
my $z = IO::Compress::Zip->new("-", Name => "hello.txt", Stream => 1)
Now the contents of the zip file look like this:
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:22 hello.txt
--------- -------
12 1 file
π¦ Compressing a file from the filesystem π¦
To read the contents of the file file1.txt and write the compressed data to the file file1.txt.zip, there are a few options.
Start by creating the compression object and opening the input file:
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my $input = "file1.txt";
my $z = IO::Compress::Zip->new("file1.txt.zip")
or die "IO::Compress::Zip failed: $ZipError\n";
# open the input file
open my $fh, "<", "file1.txt"
or die "Cannot open file1.txt: $!\n";
# loop through the input file & write to the compressed file
while (<$fh>) {
$z->print($_);
}
# not forgetting to close the compressed file
$z->close();
π§ Compressing multiple files π§
To create a zip file, output.zip, that contains the compressed contents of the files alpha.txt and beta.txt:
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my $z = IO::Compress::Zip->new("output.zip", Name => "alpha.txt")
or die "IO::Compress::Zip failed: $ZipError\n";
# open the input file
open my $fh, "<", "file1.txt"
or die "Cannot open file1.txt: $!\n";
# loop through the input file & write to the compressed file
while (<$fh>) {
$z->print($_);
}
# move to next file
$z->newStream(Name => "beta.txt")
while (<$fh>) {
$z->print($_);
}
$z->close();
π οΈ Methods π οΈ
okay bestie, hereβs the method menu for your $z object π
every single one is staying, no skips, no βoops I forgot that oneβ energy.
β¨ print β¨
call it like:
$z->print($data)
print $z $data
Compresses and outputs the contents of the $data parameter. This has the same behaviour as the print built-in.
Returns true if successful.
β¨ printf β¨
call it like:
$z->printf($format, $data)
printf $z $format, $data
Compresses and outputs the contents of the $data parameter.
Returns true if successful.
β¨ syswrite β¨
call it like:
$z->syswrite $data
$z->syswrite $data, $length
$z->syswrite $data, $length, $offset
Compresses and outputs the contents of the $data parameter.
Returns the number of uncompressed bytes written, or undef if unsuccessful.
β¨ write β¨
call it like:
$z->write $data
$z->write $data, $length
$z->write $data, $length, $offset
Compresses and outputs the contents of the $data parameter.
Returns the number of uncompressed bytes written, or undef if unsuccessful.
β¨ flush β¨
call it like:
$z->flush;
$z->flush($flush_type);
Flushes any pending compressed data to the output file/buffer.
This method takes an optional parameter, $flush_type, that controls how the flushing will be carried out. By default the $flush_type used is Z_FINISH. Other valid values for $flush_type are Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH and Z_BLOCK.
β οΈ serious business: it is strongly recommended that you only set theflush_typeparameter if you fully understand the implications of what it does β overuse offlushcan seriously degrade the level of compression achieved. See thezlibdocumentation for details.
Returns true on success.
β¨ tell β¨
call it like:
$z->tell()
tell $z
Returns the uncompressed file offset.
β¨ eof β¨
call it like:
$z->eof();
eof($z);
Returns true if the close method has been called.
β¨ seek β¨
call it like:
$z->seek($position, $whence);
seek($z, $position, $whence);
Provides a sub-set of the seek functionality, with the restriction that it is only legal to seek forward in the output file/buffer. It is a fatal error to attempt to seek backward.
Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
The $whence parameter takes one the usual values, namely SEEK_SET, SEEK_CUR or SEEK_END.
Returns 1 on success, 0 on failure.
β¨ binmode β¨
call it like:
$z->binmode
binmode $z ;
This is a noop provided for completeness.
β¨ opened β¨
call it like:
$z->opened()
Returns true if the object currently refers to a opened file/buffer.
β¨ autoflush β¨
call it like:
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
If the $z object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If EXPR is present, and is non-zero, it will enable flushing after every write/print operation.
If $z is associated with a buffer, this method has no effect and always returns undef.
Note that the special variable $| cannot be used to set or retrieve the autoflush setting.
β¨ input_line_number β¨
call it like:
$z->input_line_number()
$z->input_line_number(EXPR)
This method always returns undef when compressing.
β¨ fileno β¨
call it like:
$z->fileno()
fileno($z)
If the $z object is associated with a file or a filehandle, fileno will return the underlying file descriptor. Once the close method is called fileno will return undef.
If the $z object is associated with a buffer, this method will return undef.
β¨ close β¨
call it like:
$z->close() ;
close $z ;
Flushes any pending compressed data and then closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Compress::Zip object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the close method will be called automatically, but not until global destruction of all live objects when the program is terminating.
π so if u want your scripts to run on all versions of Perl, call close explicitly and do not rely on automatic closing, bestie.
Returns true on success, otherwise 0.
If the AutoClose option has been enabled when the IO::Compress::Zip object was created, and the object is associated with a file, the underlying file will also be closed.
β¨ newStream([OPTS]) β¨
call it like:
$z->newStream( [OPTS] )
Closes the current compressed data stream and starts a new one.
OPTS consists of any of the options that are available when creating the $z object.
See the Constructor Options section for more details.
β¨ deflateParams β¨
call it like:
$z->deflateParams
TODO
π Importing π
A number of symbolic constants are required by some methods in IO::Compress::Zip. None are imported by default.
:allβ Importszip,$ZipErrorand all symbolic constants that can be used byIO::Compress::Zip. Same as doing this:
use IO::Compress::Zip qw(zip $ZipError :constants) ;
:constantsβ Import all symbolic constants. Same as doing this:
use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
:flushβ These symbolic constants are used by theflushmethod.
Z_NO_FLUSH
Z_PARTIAL_FLUSH
Z_SYNC_FLUSH
Z_FULL_FLUSH
Z_FINISH
Z_BLOCK
:levelβ These symbolic constants are used by theLeveloption in the constructor.
Z_NO_COMPRESSION
Z_BEST_SPEED
Z_BEST_COMPRESSION
Z_DEFAULT_COMPRESSION
:strategyβ These symbolic constants are used by theStrategyoption in the constructor.
Z_FILTERED
Z_HUFFMAN_ONLY
Z_RLE
Z_FIXED
Z_DEFAULT_STRATEGY
:zip_methodβ These symbolic constants are used by theMethodoption in the constructor.
ZIP_CM_STORE
ZIP_CM_DEFLATE
ZIP_CM_BZIP2
π¦ EXAMPLES π¦
β¨ Apache::GZip Revisited β¨
See IO::Compress::FAQ
β¨ Working with Net::FTP β¨
See IO::Compress::FAQ
π SUPPORT π
General feedback/questions/bug reports should be sent to https://github.com/pmqs/IO-Compress/issues (preferred) or https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress.
π SEE ALSO π
Compress::ZlibIO::Compress::GzipIO::Uncompress::GunzipIO::Compress::DeflateIO::Uncompress::InflateIO::Compress::RawDeflateIO::Uncompress::RawInflateIO::Compress::Bzip2IO::Uncompress::Bunzip2IO::Compress::LzmaIO::Uncompress::UnLzmaIO::Compress::XzIO::Uncompress::UnXzIO::Compress::LzipIO::Uncompress::UnLzipIO::Compress::LzopIO::Uncompress::UnLzopIO::Compress::LzfIO::Uncompress::UnLzfIO::Compress::ZstdIO::Uncompress::UnZstdIO::Uncompress::AnyInflateIO::Uncompress::AnyUncompressIO::Compress::FAQFile::GlobMapper,Archive::Zip,Archive::Tar,IO::Zlib
For RFC 1950, 1951 and 1952 see https://datatracker.ietf.org/doc/html/rfc1950, https://datatracker.ietf.org/doc/html/rfc1951 and https://datatracker.ietf.org/doc/html/rfc1952
The zlib compression library was written by Jean-loup Gailly gzip@prep.ai.mit.edu and Mark Adler madler@alumni.caltech.edu.
The primary site for the zlib compression library is http://www.zlib.org.
The primary site for the zlib-ng compression library is https://github.com/zlib-ng/zlib-ng.
The primary site for gzip is http://www.gzip.org.
π AUTHOR π
This module was written by Paul Marquess, pmqs@cpan.org.
β MODIFICATION HISTORY β
See the Changes file.
π COPYRIGHT AND LICENSE π
Copyright (c) 2005-2026 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
okay thatβs the whole manual page, bestie π this was IO::Compress::Zip(3pm), from perl v5.42.3, dated 2026-11-03 β¨ no cap, u got this π«Ά
π¦ where this page comes from
- alpine 3.24: perl-doc 5.42.3-r0 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms