π Archive::Zip - Provide an interface to ZIP archive files.
| Use Case | Command | Description |
|---|---|---|
| π Create a new empty zip | my $zip = Archive::Zip->new(); | π Create a new empty zip archive object. |
| π Add a directory to zip | $zip->addDirectory('dirname/'); | β Append a directory member to the zip. |
| π Add a string as a file | $zip->addString('content', 'name.txt'); | β Append a member from a string, set compression if desired. |
| π Add a file from disk | $zip->addFile('file.pl', 'newname.pl'); | β Append a member from an external file, optionally rename. |
| πΎ Save zip to file | $zip->writeToFileNamed('output.zip'); | πΎ Write the zip archive to a named file, returns AZ_OK. |
| π Read an existing zip | $zip->read('input.zip'); | π Read zipfile headers from a file, appending members. |
| π Get member by name | $zip->memberNamed('filename.txt'); | π Return reference to member matching given internal filename. |
| π Extract member contents | $zip->contents('member.txt'); | π Return uncompressed data for a member, or set new contents. |
| π Extract all files | $zip->extractTree(); | π Extract all files in the zip with original names. |
| ποΈ Remove a member | $zip->removeMember('member.txt'); | ποΈ Remove and return the given member or name. |
| π Update member from file | $zip->updateMember('member.txt', 'newfile.txt'); | π Update a single member from a file if changed. |
| π³ Add entire directory tree | $zip->addTree('.', 'dest'); | π³ Add all readable files and directories below root as dest/*. |
# Create a Zip file
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
my $zip = Archive::Zip->new();
# Add a directory
my $dir_member = $zip->addDirectory( 'dirname/' );
# Add a file from a string with compression
my $string_member = $zip->addString( 'This is a test', 'stringMember.txt' );
$string_member->desiredCompressionMethod( COMPRESSION_DEFLATED );
# Add a file from disk
my $file_member = $zip->addFile( 'xyz.pl', 'AnotherName.pl' );
# Save the Zip file
unless ( $zip->writeToFileNamed('someZip.zip') == AZ_OK ) {
die 'write error';
}
# Read a Zip file
my $somezip = Archive::Zip->new();
unless ( $somezip->read( 'someZip.zip' ) == AZ_OK ) {
die 'read error';
}
# Change the compression type for a file in the Zip
my $member = $somezip->memberNamed( 'stringMember.txt' );
$member->desiredCompressionMethod( COMPRESSION_STORED );
unless ( $zip->writeToFileNamed( 'someOtherZip.zip' ) == AZ_OK ) {
die 'write error';
}
π The Archive::Zip module allows a Perl program to create, manipulate, read, and write Zip archive files.
π¦ Zip archives can be created, or you can read from existing zip files.
πΎ Once created, they can be written to files, streams, or strings. Members can be added, removed, extracted, replaced, rearranged, and enumerated. They can also be renamed or have their dates, comments, or other attributes queried or modified. Their data can be compressed or uncompressed as needed.
π Members can be created from members in existing Zip files, or from existing directories, files, or strings.
π§° This module uses the Compress::Raw::Zlib library to read and write the compressed streams inside the files.
π One can use Archive::Zip::MemberRead to read the zip file archive members as if they were files.
Regardless of what your local file system uses for file naming, names in a Zip file are in Unix format (forward slashes (/) separating directory names, etc.).
βArchive::Zipβ tries to be consistent with file naming conventions, and will translate back and forth between native and Zip file names.
However, it canβt guess which format names are in. So two rules control what kind of file name you must pass various routines:
π¦ Archive::Zip::Archive objects are what you ordinarily deal with. These maintain the structure of a zip file, without necessarily holding data. When a zip is read from a disk file, the (possibly compressed) data still lives in the file, not in memory. Archive members hold information about the individual members, but not (usually) the actual member data. When the zip is written to a (different) file, the member data is compressed or copied as needed. It is possible to make archive members whose data is held in a string in memory, but this is not done when a zip file is read. Directory members donβt have any data.
Exporter
Archive::Zip Common base class, has defs.
Archive::Zip::Archive A Zip archive.
Archive::Zip::Member Abstract superclass for all members.
Archive::Zip::StringMember Member made from a string
Archive::Zip::FileMember Member made from an external file
Archive::Zip::ZipFileMember Member that lives in a zip file
Archive::Zip::NewFileMember Member whose data is in a file
Archive::Zip::DirectoryMember Member that is a directory
Exports the following constants:
FA_MSDOS FA_UNIX GPBF_ENCRYPTED_MASKGPBF_DEFLATING_COMPRESSION_MASK GPBF_HAS_DATA_DESCRIPTOR_MASKCOMPRESSION_STORED COMPRESSION_DEFLATED IFA_TEXT_FILE_MASKIFA_TEXT_FILE IFA_BINARY_FILE COMPRESSION_LEVEL_NONECOMPRESSION_LEVEL_DEFAULT COMPRESSION_LEVEL_FASTESTCOMPRESSION_LEVEL_BEST_COMPRESSION ZIP64_SUPPORTED ZIP64_AS_NEEDEDZIP64_EOCD ZIP64_HEADERSExports the following constants (only necessary for extending the module):
FA_AMIGA FA_VAX_VMS FA_VM_CMS FA_ATARI_ST FA_OS2_HPFS FA_MACINTOSHFA_Z_SYSTEM FA_CPM FA_WINDOWS_NTFSGPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASKGPBF_IMPLODING_3_SHANNON_FANO_TREES_MASKGPBF_IS_COMPRESSED_PATCHED_DATA_MASK COMPRESSION_SHRUNKDEFLATING_COMPRESSION_NORMAL DEFLATING_COMPRESSION_MAXIMUMDEFLATING_COMPRESSION_FAST DEFLATING_COMPRESSION_SUPER_FASTCOMPRESSION_REDUCED_1 COMPRESSION_REDUCED_2 COMPRESSION_REDUCED_3COMPRESSION_REDUCED_4 COMPRESSION_IMPLODED COMPRESSION_TOKENIZEDCOMPRESSION_DEFLATED_ENHANCEDCOMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODEDExplained below. Returned from most methods.
AZ_OK AZ_STREAM_END AZ_ERROR AZ_FORMAT_ERROR AZ_IO_ERRORMany of the methods in Archive::Zip return error codes. These are implemented as inline subroutines, using the βuse constantβ pragma. They can be imported into your namespace using the β:ERROR_CODESβ tag:
use Archive::Zip qw( :ERROR_CODES );
...
unless ( $zip->read( 'myfile.zip' ) == AZ_OK ) {
die "whoops!";
}
AZ_OK (0) β β
Everything is fine.AZ_STREAM_END (1) β π The read stream (or central directory) ended normally.AZ_ERROR (2) β β There was some generic kind of error.AZ_FORMAT_ERROR (3) β π« There is a format error in a ZIP file being read.AZ_IO_ERROR (4) β π₯ There was an IO error.π¦ Archive::Zip allows each member of a ZIP file to be compressed (using the Deflate algorithm) or uncompressed.
Other compression algorithms that some versions of ZIP have been able to produce are not supported. Each member has two compression methods: the one itβs stored as (this is always COMPRESSION_STORED for string and external file members), and the one you desire for the member in the zip file.
These can be different, of course, so you can make a zip member that is not compressed out of one that is, and vice versa.
You can inquire about the current compression and set the desired compression method:
my $member = $zip->memberNamed( 'xyz.txt' );
$member->compressionMethod(); # return current compression
# set to read uncompressed
$member->desiredCompressionMethod( COMPRESSION_STORED );
# set to read compressed
$member->desiredCompressionMethod( COMPRESSION_DEFLATED );
There are two different compression methods:
COMPRESSION_STORED β π File is stored (no compression)COMPRESSION_DEFLATED β ποΈ File is DeflatedIf a memberβs desiredCompressionMethod is COMPRESSION_DEFLATED, you can choose different compression levels. This choice may affect the speed of compression and decompression, as well as the size of the compressed member data.
$member->desiredCompressionLevel( 9 );
The levels given can be:
COMPRESSION_LEVEL_NONE β This is the same as saying $member->desiredCompressionMethod( COMPRESSION_STORED );COMPRESSION_LEVEL_FASTEST β This is a synonym for level 1.COMPRESSION_LEVEL_BEST_COMPRESSION β This is a synonym for level 9.COMPRESSION_LEVEL_DEFAULT β This gives a good compromise between speed and compression, and is currently equivalent to 6 (this is in the zlib code). This is the level that will be used if not specified.The Archive::Zip class (and its invisible subclass Archive::Zip::Archive) implement generic zip file functionality. Creating a new Archive::Zip object actually makes an Archive::Zip::Archive object, but you donβt have to worry about this unless youβre subclassing.
new( [$fileName] ) / new( { filename => $fileName } ) β Make a new, empty zip archive.
my $zip = Archive::Zip->new();
If an additional argument is passed, new() will call read() to read the contents of an archive:
my $zip = Archive::Zip->new( 'xyz.zip' );
If a filename argument is passed and the read fails for any reason, new will return undef. For this reason, it may be better to call read separately.These Archive::Zip methods may be called as functions or as object methods. Do not call them as class methods:
$zip = Archive::Zip->new();
$crc = Archive::Zip::computeCRC32( 'ghijkl' ); # OK
$crc = $zip->computeCRC32( 'ghijkl' ); # also OK
$crc = Archive::Zip->computeCRC32( 'ghijkl' ); # NOT OK
Archive::Zip::computeCRC32( $string [, $crc] ) / Archive::Zip::computeCRC32( { string => $string [, checksum => $crc ] } ) β This is a utility function that uses the Compress::Raw::Zlib CRC routine to compute a CRC-32. You can get the CRC of a string:
$crc = Archive::Zip::computeCRC32( $string );
Or you can compute the running CRC:
$crc = 0;
$crc = Archive::Zip::computeCRC32( 'abcdef', $crc );
$crc = Archive::Zip::computeCRC32( 'ghijkl', $crc );
Archive::Zip::setChunkSize( $number ) / Archive::Zip::setChunkSize( { chunkSize => $number } ) β Report or change chunk size used for reading and writing. This can make big differences in dealing with large files. Currently, this defaults to 32K. This also changes the chunk size used for Compress::Raw::Zlib. You must call setChunkSize() before reading or writing. This is not exportable, so you must call it like:
Archive::Zip::setChunkSize( 4096 );
or as a method on a zip (though this is a global setting). Returns old chunk size.Archive::Zip::chunkSize() β Returns the current chunk size:
my $chunkSize = Archive::Zip::chunkSize();
Archive::Zip::setErrorHandler( \&subroutine ) / Archive::Zip::setErrorHandler( { subroutine => \&subroutine } ) β Change the subroutine called with error strings. This defaults to \&Carp::carp, but you may want to change it to get the error strings. This is not exportable, so you must call it like:
Archive::Zip::setErrorHandler( \&myErrorHandler );
If myErrorHandler is undef, resets handler to default. Returns old error handler. Note that if you call Carp::carp or a similar routine or if youβre chaining to the default error handler from your error handler, you may want to increment the number of caller levels that are skipped (do not just set it to a number):
$Carp::CarpLevel++;
Archive::Zip::tempFile( [ $tmpdir ] ) / Archive::Zip::tempFile( { tempDir => $tmpdir } ) β Create a uniquely named temp file. It will be returned open for read/write. If $tmpdir is given, it is used as the name of a directory to create the file in. If not given, creates the file using βFile::Spec::tmpdir()β. Generally, you can override this choice using the $ENV{TMPDIR} environment variable. But see the File::Spec documentation for your system. Note that on many systems, if youβre running in taint mode, then you must make sure that $ENV{TMPDIR} is untainted for it to be used. Will NOT create $tmpdir if it does not exist (this is a change from prior versions!). Returns file handle and name:
my ($fh, $name) = Archive::Zip::tempFile();
my ($fh, $name) = Archive::Zip::tempFile('myTempDir');
my $fh = Archive::Zip::tempFile(); # if you don't need the name
members() β Return a copy of the members array
my @members = $zip->members();
numberOfMembers() β Return the number of members I havememberNames() β Return a list of the (internal) file names of the zip membersmemberNamed( $string ) / memberNamed( { zipName => $string } ) β Return ref to member whose filename equals given filename or undef. $string must be in Zip (Unix) filename format.membersMatching( $regex ) / membersMatching( { regex => $regex } ) β Return array of members whose filenames match given regular expression in list context. Returns number of matching members in scalar context.
my @textFileMembers = $zip->membersMatching( '.*\.txt' );
# or
my $numberOfTextFiles = $zip->membersMatching( '.*\.txt' );
zip64() β Returns whether the previous read or write of the archive has been done in zip64 format.desiredZip64Mode() β Gets or sets which parts of the archive should be written in zip64 format: All parts as needed (ZIP64_AS_NEEDED), the default, force writing the zip64 end of central directory record (ZIP64_EOCD), force writing the zip64 EOCD record and all headers in zip64 format (ZIP64_HEADERS).versionMadeBy() / versionNeededToExtract() β Gets the fields from the zip64 end of central directory record. These are always 0 if the archive is not in zip64 format.diskNumber() β Return the disk that I start on. Not used for writing zips, but might be interesting if you read a zip in. This should be 0, as Archive::Zip does not handle multi-volume archives.diskNumberWithStartOfCentralDirectory() β Return the disk number that holds the beginning of the central directory. Not used for writing zips, but might be interesting if you read a zip in. This should be 0, as Archive::Zip does not handle multi-volume archives.numberOfCentralDirectoriesOnThisDisk() β Return the number of CD structures in the zipfile last read in. Not used for writing zips, but might be interesting if you read a zip in.numberOfCentralDirectories() β Return the number of CD structures in the zipfile last read in. Not used for writing zips, but might be interesting if you read a zip in.centralDirectorySize() β Returns central directory size, as read from an external zip file. Not used for writing zips, but might be interesting if you read a zip in.centralDirectoryOffsetWRTStartingDiskNumber() β Returns the offset into the zip file where the CD begins. Not used for writing zips, but might be interesting if you read a zip in.zipfileComment( [ $string ] ) / zipfileComment( [ { comment => $string } ] ) β Get or set the zipfile comment. Returns the old comment.
print $zip->zipfileComment();
$zip->zipfileComment( 'New Comment' );
eocdOffset() β Returns the (unexpected) number of bytes between where the EOCD was found and where it expected to be. This is normally 0, but would be positive if something (a virus, perhaps) had added bytes somewhere before the EOCD. Not used for writing zips, but might be interesting if you read a zip in. Here is an example of how you can diagnose this:
my $zip = Archive::Zip->new('somefile.zip');
if ($zip->eocdOffset())
{
warn "A virus has added ", $zip->eocdOffset, " bytes of garbage\n";
}
The βeocdOffset()β is used to adjust the starting position of member headers, if necessary.fileName() β Returns the name of the file last read from. If nothing has been read yet, returns an empty string; if read from a file handle, returns the handle in string form.Various operations on a zip file modify members. When a member is passed as an argument, you can either use a reference to the member itself, or the name of a member. Of course, using the name requires that names be unique within a zip (this is not enforced).
removeMember( $memberOrName ) / removeMember( { memberOrZipName => $memberOrName } ) β Remove and return the given member, or match its name and remove it. Returns undef if member or name does not exist in this Zip. No-op if member does not belong to this zip.replaceMember( $memberOrName, $newMember ) / replaceMember( { memberOrZipName => $memberOrName, newMember => $newMember } ) β Remove and return the given member, or match its name and remove it. Replace with new member. Returns undef if member or name does not exist in this Zip, or if $newMember is undefined.
my $member1 = $zip->removeMember( 'xyz' );
my $member2 = $zip->replaceMember( 'abc', $member1 );
# now, $member2 (named 'abc') is not in $zip,
# and $member1 (named 'xyz') is, having taken $member2's place.
extractMember( $memberOrName [, $extractedName ] ) / extractMember( { memberOrZipName => $memberOrName [, name => $extractedName ] } ) β Extract the given member, or match its name and extract it. Returns undef if member does not exist in this Zip. If optional second arg is given, use it as the name of the extracted member. Otherwise, the internal filename of the member is used as the name of the extracted file or directory. If you pass $extractedName, it should be in the local file systemβs format. If you do not pass $extractedName and the internal filename traverses a parent directory or a symbolic link, the extraction will be aborted with βAC_ERRORβ for security reason. All necessary directories will be created. Returns βAZ_OKβ on success.extractMemberWithoutPaths( $memberOrName [, $extractedName ] ) / extractMemberWithoutPaths( { memberOrZipName => $memberOrName [, name => $extractedName ] } ) β Extract the given member, or match its name and extract it. Does not use path information (extracts into the current directory). Returns undef if member does not exist in this Zip. If optional second arg is given, use it as the name of the extracted member (its paths will be deleted too). Otherwise, the internal filename of the member (minus paths) is used as the name of the extracted file or directory. Returns βAZ_OKβ on success. If you do not pass $extractedName and the internal filename is equalled to a local symbolic link, the extraction will be aborted with βAC_ERRORβ for security reason.addMember( $member ) / addMember( { member => $member } ) β Append a member (possibly from another zip file) to the zip file. Returns the new member. Generally, you will use addFile(), addDirectory(), addFileOrDirectory(), addString(), or read() to add members.
# Move member named 'abc' to end of zip:
my $member = $zip->removeMember( 'abc' );
$zip->addMember( $member );
updateMember( $memberOrName, $fileName ) / updateMember( { memberOrZipName => $memberOrName, name => $fileName } ) β Update a single member from the file or directory named $fileName. Returns the (possibly added or updated) member, if any; βundefβ on errors. The comparison is based on βlastModTime()β and (in the case of a non-directory) the size of the file.addFile( $fileName [, $newName, $compressionLevel ] ) / addFile( { filename => $fileName [, zipName => $newName, compressionLevel => $compressionLevel } ] ) β Append a member whose data comes from an external file, returning the member or undef. The member will have its file name set to the name of the external file, and its desiredCompressionMethod set to COMPRESSION_DEFLATED. The file attributes and last modification time will be set from the file. If the name given does not represent a readable plain file or symbolic link, undef will be returned. $fileName must be in the format required for the local file system. The optional $newName argument sets the internal file name to something different than the given $fileName. $newName, if given, must be in Zip name format (i.e. Unix). The text mode bit will be set if the contents appears to be text (as returned by the β-Tβ perl operator). NOTE that you should not (generally) use absolute path names in zip member names, as this will cause problems with some zip tools as well as introduce a security hole and make the zip harder to use.addDirectory( $directoryName [, $fileName ] ) / addDirectory( { directoryName => $directoryName [, zipName => $fileName ] } ) β Append a member created from the given directory name. The directory name does not have to name an existing directory. If the named directory exists, the file modification time and permissions are set from the existing directory, otherwise they are set to now and permissive default permissions. $directoryName must be in local file system format. The optional second argument sets the name of the archive member (which defaults to $directoryName). If given, it must be in Zip (Unix) format. Returns the new member.addFileOrDirectory( $name [, $newName, $compressionLevel ] ) / addFileOrDirectory( { name => $name [, zipName => $newName, compressionLevel => $compressionLevel ] } ) β Append a member from the file or directory named $name. If $newName is given, use it for the name of the new member. Will add or remove trailing slashes from $newName as needed. $name must be in local file system format. The optional second argument sets the name of the archive member (which defaults to $name). If given, it must be in Zip (Unix) format.addString( $stringOrStringRef, $name, [$compressionLevel] ) / addString( { string => $stringOrStringRef [, zipName => $name, compressionLevel => $compressionLevel ] } ) β Append a member created from the given string or string reference. The name is given by the second argument. Returns the new member. The last modification time will be set to now, and the file attributes will be set to permissive defaults.
my $member = $zip->addString( 'This is a test', 'test.txt' );
contents( $memberOrMemberName [, $newContents ] ) / contents( { memberOrZipName => $memberOrMemberName [, contents => $newContents ] } ) β Returns the uncompressed data for a particular member, or undef.
print "xyz.txt contains " . $zip->contents( 'xyz.txt' );
Also can change the contents of a member:
$zip->contents( 'xyz.txt', 'This is the new contents' );
If called expecting an array as the return value, it will include the status as the second value in the array.
($content, $status) = $zip->contents( 'xyz.txt');
A Zip archive can be written to a file or file handle, or read from one.
writeToFileNamed( $fileName ) / writeToFileNamed( { fileName => $fileName } ) β Write a zip archive to named file. Returns βAZ_OKβ on success.
my $status = $zip->writeToFileNamed( 'xx.zip' );
die "error somewhere" if $status != AZ_OK;
Note that if you use the same name as an existing zip file that you read in, you will clobber ZipFileMembers. So instead, write to a different file name, then delete the original. If you use the βoverwrite()β or βoverwriteAs()β methods, you can re-write the original zip in this way. $fileName should be a valid file name on your system.writeToFileHandle( $fileHandle [, $seekable] ) β Write a zip archive to a file handle. Return AZ_OK on success. The optional second arg tells whether or not to try to seek backwards to re-write headers. If not provided, it is set if the Perl β-fβ test returns true. This could fail on some operating systems, though.
my $fh = IO::File->new( 'someFile.zip', 'w' );
unless ( $zip->writeToFileHandle( $fh ) == AZ_OK ) {
# error handling
}
If you pass a file handle that is not seekable (like if youβre writing to a pipe or a socket), pass a false second argument:
my $fh = IO::File->new( '| cat > somefile.zip', 'w' );
$zip->writeToFileHandle( $fh, 0 ); # fh is not seekable
If this method fails during the write of a member, that member and all following it will return false from βwasWritten()β. See writeCentralDirectory() for a way to deal with this. If you want, you can write data to the file handle before passing it to writeToFileHandle(); this could be used (for instance) for making self-extracting archives. However, this only works reliably when writing to a real file (as opposed to STDOUT or some other possible non-file). See examples/selfex.pl for how to write a self-extracting archive.writeCentralDirectory( $fileHandle [, $offset ] ) / writeCentralDirectory( { fileHandle => $fileHandle [, offset => $offset ] } ) β Writes the central directory structure to the given file handle. Returns AZ_OK on success. If given an $offset, will seek to that point before writing. This can be used for recovery in cases where writeToFileHandle or writeToFileNamed returns an IO error because of running out of space on the destination file.
my $fh = IO::File->new( 'someFile.zip', 'w' );
my $retval = $zip->writeToFileHandle( $fh );
if ( $retval == AZ_IO_ERROR ) {
my @unwritten = grep { not $_->wasWritten() } $zip->members();
if (@unwritten) {
$zip->removeMember( $member ) foreach my $member ( @unwritten );
$zip->writeCentralDirectory( $fh,
$unwritten[0]->writeLocalHeaderRelativeOffset());
}
}
overwriteAs( $newName ) / overwriteAs( { filename => $newName } ) β Write the zip to the specified file, as safely as possible. This is done by first writing to a temp file, then renaming the original if it exists, then renaming the temp file, then deleting the renamed original if it exists. Returns AZ_OK if successful.overwrite() β Write back to the original zip file. See overwriteAs() above. If the zip was not ever read from a file, this generates an error.read( $fileName ) / read( { filename => $fileName } ) β Read zipfile headers from a zip file, appending new members. Returns βAZ_OKβ or error code.
my $zipFile = Archive::Zip->new();
my $status = $zipFile->read( '/some/FileName.zip' );
readFromFileHandle( $fileHandle, $filename ) / readFromFileHandle( { fileHandle => $fileHandle, filename => $filename } ) β Read zipfile headers from an already-opened file handle, appending new members. Does not close the file handle. Returns βAZ_OKβ or error code. Note that this requires a seekable file handle; reading from a stream is not yet supported, but using in-memory data is.
my $fh = IO::File->new( '/some/FileName.zip', 'r' );
my $zip1 = Archive::Zip->new();
my $status = $zip1->readFromFileHandle( $fh );
my $zip2 = Archive::Zip->new();
$status = $zip2->readFromFileHandle( $fh );
Read zip using in-memory data (recursable):
open my $fh, "
Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-14 21:26 @2600:1f28:365:80b0:4d23:66fa:c2bb:7bae
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)