Archive::Zip â Provide an interface to ZIP archive files.
| Use Case | Command | Description |
|---|---|---|
| đĻ Create a new Zip | Archive::Zip->new() | Create an empty zip archive object |
| â Add a directory | $zip->addDirectory('dirname/') | Append a directory member to the zip |
| â Add a string as file | $zip->addString($string, $name) | Append a member from a string with optional compression |
| â Add a file from disk | $zip->addFile('file.pl', 'zipName.pl') | Append a member from an external file |
| đž Write zip to file | $zip->writeToFileNamed('out.zip') | Save the archive to a named file |
| đ Read zip from file | $zip->read('file.zip') | Read zipfile headers and append members |
| đ List members | $zip->members() | Return array of all member objects |
| đ Find member by name | $zip->memberNamed('name') | Return member ref or undef |
| đ Get member contents | $zip->contents('member') | Return uncompressed data for a member |
| đī¸ Set compression | $member->desiredCompressionMethod(COMPRESSION_DEFLATED) | Change compression method for a member |
| đ˛ Add entire directory tree | $zip->addTree('.', 'prefix') | Recursively add files from a directory |
| đŗ Extract all files | $zip->extractTree() | Extract all members with original names |
# 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:
File::Spec and File::Basename are used for various file operations. When you're referring to a file on your system, use its file naming conventions.extract() methods that can take one or two names will convert from local to zip names if you call them with a single name.Overview
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
FA_MSDOS FA_UNIX GPBF_ENCRYPTED_MASK GPBF_DEFLATING_COMPRESSION_MASK GPBF_HAS_DATA_DESCRIPTOR_MASK COMPRESSION_STORED COMPRESSION_DEFLATED IFA_TEXT_FILE_MASK IFA_TEXT_FILE IFA_BINARY_FILE COMPRESSION_LEVEL_NONE COMPRESSION_LEVEL_DEFAULT COMPRESSION_LEVEL_FASTEST COMPRESSION_LEVEL_BEST_COMPRESSION ZIP64_SUPPORTED ZIP64_AS_NEEDED ZIP64_EOCD ZIP64_HEADERSFA_AMIGA FA_VAX_VMS FA_VM_CMS FA_ATARI_ST FA_OS2_HPFS FA_MACINTOSH FA_Z_SYSTEM FA_CPM FA_WINDOWS_NTFS GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK GPBF_IS_COMPRESSED_PATCHED_DATA_MASK COMPRESSION_SHRUNK DEFLATING_COMPRESSION_NORMAL DEFLATING_COMPRESSION_MAXIMUM DEFLATING_COMPRESSION_FAST DEFLATING_COMPRESSION_SUPER_FAST COMPRESSION_REDUCED_1 COMPRESSION_REDUCED_2 COMPRESSION_REDUCED_3 COMPRESSION_REDUCED_4 COMPRESSION_IMPLODED COMPRESSION_TOKENIZED COMPRESSION_DEFLATED_ENHANCED COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODEDAZ_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.| Code | Constant | Description |
|---|---|---|
| 0 | AZ_OK | â Success |
| 1 | AZ_STREAM_END | â Stream ended normally |
| 2 | AZ_ERROR | â Generic error |
| 3 | AZ_FORMAT_ERROR | â Format error in ZIP file |
| 4 | AZ_IO_ERROR | â I/O 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:
0 or COMPRESSION_LEVEL_NONE â Same as $member->desiredCompressionMethod( COMPRESSION_STORED )1 .. 9 â 1 gives best speed and worst compression; 9 gives best compression and worst speedCOMPRESSION_LEVEL_FASTEST â Synonym for level 1COMPRESSION_LEVEL_BEST_COMPRESSION â Synonym for level 9COMPRESSION_LEVEL_DEFAULT â Good compromise (currently equivalent to 6); this is the defaultThe 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. If an additional argument is passed, new() will call read() to read the contents of an archive. If the read fails, new returns undef.
my $zip = Archive::Zip->new();
my $zip = Archive::Zip->new( 'xyz.zip' );
These 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] ) â Compute a CRC-32 using Compress::Raw::Zlib. Can get CRC of a string or compute a running CRC.Archive::Zip::setChunkSize( $number ) â Report or change chunk size used for reading and writing (default 32K). Must be called before reading or writing. Returns old chunk size.Archive::Zip::chunkSize() â Returns the current chunk size.Archive::Zip::setErrorHandler( \&subroutine ) â Change the subroutine called with error strings. Defaults to \&Carp::carp. Returns old error handler.Archive::Zip::tempFile( [ $tmpdir ] ) â Create a uniquely named temp file, returned open for read/write. Returns file handle and name.members() â Return a copy of the members arraynumberOfMembers() â Return the number of membersmemberNames() â Return a list of the (internal) file names of the zip membersmemberNamed( $string ) â Return ref to member whose filename equals given filename or undef. $string must be in Zip (Unix) format.membersMatching( $regex ) â Return array of members whose filenames match given regex in list context; returns count in scalar context.zip64() â Returns whether the previous read or write was done in zip64 format.desiredZip64Mode() â Gets or sets zip64 writing mode: ZIP64_AS_NEEDED (default), ZIP64_EOCD, or ZIP64_HEADERS.versionMadeBy() â Gets the field from the zip64 end of central directory record.versionNeededToExtract() â Gets the field from the zip64 end of central directory record.diskNumber() â Return the disk that I start on (should be 0).diskNumberWithStartOfCentralDirectory() â Return the disk number that holds the beginning of the central directory.numberOfCentralDirectoriesOnThisDisk() â Return the number of CD structures in the zipfile last read in.numberOfCentralDirectories() â Return the number of CD structures in the zipfile last read in.centralDirectorySize() â Returns central directory size from an external zip file.centralDirectoryOffsetWRTStartingDiskNumber() â Returns the offset where the CD begins.zipfileComment( [ $string ] ) â Get or set the zipfile comment. Returns the old comment.eocdOffset() â Returns the (unexpected) number of bytes between where the EOCD was found and where it expected to be (normally 0). Useful for virus detection.fileName() â Returns the name of the file last read from.removeMember( $memberOrName ) â Remove and return the given member, or match its name and remove it. Returns undef if not found.replaceMember( $memberOrName, $newMember ) â Remove and return the given member, or match its name and remove it. Replace with new member. Returns undef if not found.extractMember( $memberOrName [, $extractedName ] ) â Extract the given member, or match its name and extract it. Returns undef if not found. Returns AZ_OK on success.extractMemberWithoutPaths( $memberOrName [, $extractedName ] ) â Extract without path information (into current directory). Returns AZ_OK on success.addMember( $member ) â Append a member (possibly from another zip file) to the zip file. Returns the new member.updateMember( $memberOrName, $fileName ) â Update a single member from the file or directory named $fileName. Returns the (possibly added or updated) member, or undef on errors.addFile( $fileName [, $newName, $compressionLevel ] ) â Append a member from an external file, returning the member or undef. The member will have desiredCompressionMethod set to COMPRESSION_DEFLATED.addDirectory( $directoryName [, $fileName ] ) â Append a member created from the given directory name. Returns the new member.addFileOrDirectory( $name [, $newName, $compressionLevel ] ) â Append a member from the file or directory named $name.addString( $stringOrStringRef, $name, [$compressionLevel] ) â Append a member created from the given string or string reference. Returns the new member.contents( $memberOrMemberName [, $newContents ] ) â Returns the uncompressed data for a particular member, or undef. Can also change the contents of a member.writeToFileNamed( $fileName ) â Write a zip archive to named file. Returns AZ_OK on success.writeToFileHandle( $fileHandle [, $seekable] ) â Write a zip archive to a file handle. Return AZ_OK on success. The optional second arg tells whether to try to seek backwards to re-write headers.writeCentralDirectory( $fileHandle [, $offset ] ) â Writes the central directory structure to the given file handle. Returns AZ_OK on success.overwriteAs( $newName ) â Write the zip to the specified file, as safely as possible (temp file, rename, delete original). Returns AZ_OK if successful.overwrite() â Write back to the original zip file. See overwriteAs().read( $fileName ) â Read zipfile headers from a zip file, appending new members. Returns AZ_OK or error code.readFromFileHandle( $fileHandle, $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. Requires a seekable file handle.These enable operation on an entire tree of members or files.
use Archive::Zip;
my $zip = Archive::Zip->new();
# add all readable files and directories below . as xyz/*
$zip->addTree( '.', 'xyz' );
# add all readable plain files below /abc as def/*
$zip->addTree( '/abc', 'def', sub { -f && -r } );
# add all .c files below /tmp as stuff/*
$zip->addTreeMatching( '/tmp', 'stuff', '\.c$' );
# add all .o files below /tmp as stuff/* if they aren't writable
$zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { ! -w } );
# add all .so files below /tmp that are smaller than 200 bytes as stuff/*
$zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { -s < 200 } );
# and write them into a file
$zip->writeToFileNamed('xxx.zip');
# now extract the same files into /tmpx
$zip->extractTree( 'stuff', '/tmpx' );
$zip->addTree( $root, $dest [, $pred, $compressionLevel ] ) â Add tree of files to a zip. $root is the root directory on your system. $dest is the name for the root in the zip file. $pred is an optional subroutine to select files. Returns AZ_OK on success.$zip->addTreeMatching( $root, $dest, $pattern [, $pred, $compressionLevel ] ) â Add tree of files matching a regex pattern. $pattern is a non-anchored regular expression for filenames to match.$zip->updateTree( $root [, $dest , $pred , $mirror, $compressionLevel ] ) â Update a zip file from a directory tree. Checks whether files already exist and have been changed. If $mirror is true, delete members if corresponding files were not found.$zip->extractTree( [ $root, $dest, $volume ] ) â Extract members whose names start with $root, stripping $root, and translating to $dest. If no arguments, extract all files with original names.$Archive::Zip::UNICODE â If set, file and directory names are considered to be UTF-8 encoded. EXPERIMENTAL AND BUGGY.
{
local $Archive::Zip::UNICODE = 1;
$zip->addFile('DÊjà vu.txt');
}
Several constructors allow you to construct members without adding them to a zip archive.
Archive::Zip::Member->newFromString( $stringOrStringRef [, $fileName ] ) â Construct a new member from the given string. Returns undef on error.newFromFile( $fileName [, $zipName ] ) â Construct a new member from the given file. Returns undef on error.newDirectoryNamed( $directoryName [, $zipname ] ) â Construct a new member from the given directory. $directoryName must be a valid name on your file system; it does not have to exist. Returns undef on error.These methods get (and/or set) member attribute values.
zip64() â Returns whether the previous read or write of the member has been done in zip64 format.desiredZip64Mode() â Gets or sets whether the member's headers should be written in zip64 format.versionMadeBy() â Gets the field from the member header.fileAttributeFormat( [ $format ] ) â Gets or sets the field from the member header. These are FA_* values.versionNeededToExtract() â Gets the field from the member header.bitFlag() â Gets the general purpose bit field from the member header. This is where the GPBF_* bits live.compressionMethod() â Returns the member compression method currently being used.desiredCompressionMethod( [ $method ] ) â Get or set the member's desired compression method. Returns prior desiredCompressionMethod.desiredCompressionLevel( [ $level ] ) â Get or set the member's desired compression level. Returns prior desiredCompressionLevel.externalFileName() â Return the member's external file name, if any, or undef.fileName() â Get or set the member's internal filename. Returns the (possibly new) filename.lastModFileDateTime() â Return the member's last modification date/time stamp in MS-DOS format.lastModTime() â Return the member's last modification date/time stamp, converted to unix localtime format.setLastModFileDateTimeFromUnix() â Set the member's lastModFileDateTime from the given unix time.internalFileAttributes() â Return the internal file attributes field from the zip header.externalFileAttributes() â Return member attributes as read from the ZIP file. Note: these are NOT UNIX!unixFileAttributes( [ $newAttributes ] ) â Get or set the member's file attributes using UNIX file attributes. Returns old attributes.localExtraField( [ $newField ] ) â Gets or sets the extra field from the local header. Returns AZ_OK on success, AZ_FORMAT_ERROR if invalid or contains zip64 data.cdExtraField( [ $newField ] ) â Gets or sets the extra field from the central directory header. Returns AZ_OK on success, AZ_FORMAT_ERROR if invalid or contains zip64 data.extraFields() â Return both local and CD extra fields, concatenated.fileComment( [ $newComment ] ) â Get or set the member's file comment.hasDataDescriptor() â Get or set the data descriptor flag.crc32() â Return the CRC-32 value for this member.crc32String() â Return the CRC-32 value as an 8 character printable hex string.compressedSize() â Return the compressed size for this member.uncompressedSize() â Return the uncompressed size for this member.password( [ $password ] ) â Returns the password for this member to be used on decryption.isEncrypted() â Return true if this member is encrypted.isTextFile( [ $flag ] ) â Returns true if I am a text file. Also can set the status.isBinaryFile() â Returns true if I am a binary file. Also can set the status.extractToFileNamed( $fileName ) â Extract me to a file with the given name. Returns AZ_OK on success.isDirectory() â Returns true if I am a directory.isSymbolicLink() â Returns true if I am a symbolic link.writeLocalHeaderRelativeOffset() â Returns the file offset in bytes the last time I was written.wasWritten() â Returns true if I was successfully written.It is possible to use lower-level routines to access member data streams. Example:
my ( $member, $status, $bufferRef );
$member = $zip->memberNamed( 'xyz.txt' );
$member->desiredCompressionMethod( COMPRESSION_STORED );
$status = $member->rewindData();
die "error $status" unless $status == AZ_OK;
while ( ! $member->readIsDone() )
{
( $bufferRef, $status ) = $member->readChunk();
die "error $status"
if $status != AZ_OK && $status != AZ_STREAM_END;
# do something with $bufferRef:
print $$bufferRef;
}
$member->endRead();
readChunk( [ $chunkSize ] ) â Reads the next chunk of given size from the member's data stream and compresses or uncompresses it as necessary, returning a reference to the bytes read and a status. Returns ( \$bytes, $status ).rewindData() â Rewind data and set up for reading data streams or writing zip files. Returns AZ_OK on success.endRead() â Reset the read variables and free the inflater or deflater. Returns AZ_OK on success.readIsDone() â Return true if the read has run out of data or encountered an error.contents() â Return the entire uncompressed member data or undef in scalar context. In array context, returns ( $string, $status ). Can also be used to set the contents of a member.extractToFileHandle( $fh ) â Extract (and uncompress) the member's contents to the given file handle. Return AZ_OK on success.The Archive::Zip::FileMember class extends Archive::Zip::Member and adds an externalFileName and an fh member.
externalFileName() â Return the member's external filename.fh() â Return the member's read file handle. Automatically opens file if necessary.The Archive::Zip::ZipFileMember class represents members that have been read from external zip files.
diskNumberStart() â Returns the disk number that the member's local header resides in. Should be 0.localHeaderRelativeOffset() â Returns the offset into the zip file where the member's local header is.dataOffset() â Returns the offset from the beginning of the zip file to the member's data.If you are just going to be extracting zips (and/or other archives) you are recommended to look at using Archive::Extract instead, as it is much easier to use and factors out archive-specific functionality.
Since version 1.66 Archive::Zip supports the zip64 format. On some Perl interpreters (those lacking 64-bit support or older than 5.10.0), zip64 is not supported. Constant ZIP64_SUPPORTED equals true if supported. If not supported and you try to read or write a zip64 archive, Archive::Zip returns AZ_ERROR with a message.
These fields are handled as follows:
versionMadeBy, Archive::Zip uses default value 20 (45 for zip64 EOCD) or any previously read value. It never changes that value when writing.versionNeededToExtract, Archive::Zip forces a minimum value of 45 when writing a header in zip64 format or the zip64 EOCD record.Archive::Zip never depends on these values when reading an archive.As of version 1.11, this module no longer works with IO::Scalar as it incorrectly implements seeking. Use IO::String instead, which is smaller, lighter, and perfectly compatible with regular seekable filehandles. Support for IO::Scalar will likely not be restored.
When an encrypted member is read using the wrong password, you currently have to re-read the entire archive to try again with the correct password.
Bugs should be reported on GitHub:
https://github.com/redhotpenguin/perl-Archive-Zip/issues
For other issues contact the maintainer.
Some parts copyright 2006 - 2012 Adam Kennedy.
Some parts copyright 2005 Steve Peters.
Original work copyright 2000 - 2004 Ned Konz.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Archive::Zip::MemberRead â A wrapper that allows one to read Zip archive members as if they were files.Compress::Raw::ZlibArchive::TarArchive::ExtractGenerated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 20:58 @2600:1f28:365:80b0:b91e:58eb:6587:15c8
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format