Archive::Zip - Provide an interface to ZIP archive files. |
Archive::Zip - Provide an interface to ZIP archive files.
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
my $zip = Archive::Zip->new(); my $member = $zip->addDirectory( 'dirname/' ); $member = $zip->addString( 'This is a test', 'stringMember.txt' ); $member->desiredCompressionMethod( COMPRESSION_DEFLATED ); $member = $zip->addFile( 'xyz.pl', 'AnotherName.pl' );
die 'write error' if $zip->writeToFileNamed( 'someZip.zip' ) != AZ_OK;
$zip = Archive::Zip->new(); die 'read error' if $zip->read( 'someZip.zip' ) != AZ_OK;
$member = $zip->memberNamed( 'stringMember.txt' ); $member->desiredCompressionMethod( COMPRESSION_STORED );
die 'write error' if $zip->writeToFileNamed( 'someOtherZip.zip' ) != AZ_OK;
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::Zlib library to read and write the compressed streams inside the files.
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
FA_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_IMPLODED
AZ_OK AZ_STREAM_END AZ_ERROR AZ_FORMAT_ERROR AZ_IO_ERROR
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
Many 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 :CONSTANT
tag:
use Archive::Zip qw( :CONSTANTS ); ... die "whoops!" if $zip->read( 'myfile.zip' ) != AZ_OK;
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:
If 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:
$member->desiredCompressionMethod( COMPRESSION_STORED );
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.
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
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( 4096 );
or as a method on a zip (though this is a global setting). Returns old chunk size.
This is not exportable, so you must call it like:
Archive::Zip::setErrorHandler( \&myErrorHandler );
If no error handler is passed, 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++;
members()
my @members = $zip->members();
numberOfMembers()
memberNames()
my @textFileMembers = $zip->membersMatching( '.*\.txt' ); # or my $numberOfTextFiles = $zip->membersMatching( '.*\.txt' );
diskNumber()
diskNumberWithStartOfCentralDirectory()
numberOfCentralDirectoriesOnThisDisk()
numberOfCentralDirectories()
centralDirectorySize()
centralDirectoryOffsetWRTStartingDiskNumber()
print $zip->zipfileComment(); $zip->zipfileComment( 'New Comment' );
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).
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.
All necessary directories will be created.
Returns AZ_OK
on success.
Returns AZ_OK
on success.
read()
to add members.
# Move member named 'abc' to end of zip: my $member = $zip->removeMember( 'abc' ); $zip->addMember( $member );
If the name given does not represent a readable plain file or symbolic link, undef will be returned.
The text mode bit will be set if the contents appears to be text (as returned
by the -T
perl operator).
The optional second argument sets the internal file name to something different than the given $fileName.
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' );
Returns the new member.
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' );
AZ_OK
on success.
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.
my $status = $zip->writeToFileNamed( 'xx.zip' ); die "error somewhere" if $status != AZ_OK;
The optional second arg tells whether or not to try to seek backwards to re-write headers. If not provided, it is set by testing seekability. This could fail on some operating systems, though.
my $fh = IO::File->new( 'someFile.zip', 'w' ); $zip->writeToFileHandle( $fh );
If you pass a file handle that is not seekable (like if you're writing to a pipe or a socket), pass a false as the second argument:
my $fh = IO::File->new( '| cat > somefile.zip', 'w' ); $zip->writeToFileHandle( $fh, 0 ); # fh is not seekable
AZ_OK
or error code.
my $zipFile = Archive::Zip->new(); my $status = $zipFile->read( '/some/FileName.zip' );
Several constructors allow you to construct members without adding them to a zip archive.
These work the same as the addFile(), addDirectory(), and addString()
zip instance methods described above, but they don't add the new members
to a zip.
my $member = Archive::Zip::Member->newFromString( 'This is a test', 'xyz.txt' );
my $member = Archive::Zip::Member->newFromFile( 'xyz.txt' );
my $member = Archive::Zip::Member->newDirectoryNamed( 'CVS/' );
These methods get (and/or set) member attribute values.
versionMadeBy()
FA_*
values.
versionNeededToExtract()
bitFlag()
GPBF_*
bits live.
compressionMethod()
This will be COMPRESSION_STORED for added string or file members,
or any of the COMPRESSION_*
values for members from a zip file.
However, this module can only handle members whose data is in
COMPRESSION_STORED or COMPRESSION_DEFLATED format.
Only COMPRESSION_DEFLATED or COMPRESSION_STORED are valid arguments.
Changing to COMPRESSION_STORED will change my desiredCompressionLevel to 0; changing to COMPRESSION_DEFLATED will change my desiredCompressionLevel to COMPRESSION_LEVEL_DEFAULT.
Valid arguments are 0 through 9, COMPRESSION_LEVEL_NONE, COMPRESSION_LEVEL_DEFAULT, COMPRESSION_LEVEL_BEST_COMPRESSION, and COMPRESSION_LEVEL_FASTEST.
0 or COMPRESSION_LEVEL_NONE will change the desiredCompressionMethod to COMPRESSION_STORED. All other arguments will change the desiredCompressionMethod to COMPRESSION_DEFLATED.
fileName()
Names will have backslashes converted to forward slashes, and will have multiple consecutive slashes converted to single ones.
lastModFileDateTime()
lastModTime()
print "Mod Time: " . scalar( localtime( $member->lastModTime() ) );
setLastModFileDateTimeFromUnix()
$member->setLastModFileDateTimeFromUnix( time() );
internalFileAttributes()
externalFileAttributes()
my $oldAttribs = $member->unixFileAttributes( 0666 );
Note that the return value has more than just the file permissions, so you will have to mask off the lowest bits for comparisions.
The extra field must be in the proper format.
The extra field must be in the proper format.
extraFields()
hasDataDescriptor()
This should be transparent in normal operation.
crc32()
crc32String()
compressedSize()
uncompressedSize()
isEncrypted()
isBinaryFile()
Returns AZ_OK on success.
isDirectory()
It is possible to use lower-level routines to access member data streams, rather than the extract* methods and contents().
For instance, here is how to print the uncompressed contents of a member in chunks using these methods:
my ( $member, $status, $bufferRef ); $member = $zip->memberNamed( 'xyz.txt' ); $member->desiredCompressionMethod( COMPRESSION_STORED ); $status = $member->rewindData(); die "error $status" if $status != AZ_OK; while ( ! $member->readIsDone() ) { ( $bufferRef, $status ) = $member->readChunk(); die "error $status" if $status != AZ_OK; # do something with $bufferRef: print $$bufferRef; } $member->endRead();
( \$bytes, $status)
.
my ( $outRef, $status ) = $self->readChunk(); print $$outRef if $status != AZ_OK;
rewindData()
inflateInit()
or deflateInit()
,
but this isn't likely to be necessary.
Subclass overrides should call this method.
Returns AZ_OK
on success.
endRead()
Returns AZ_OK on success.
readIsDone()
contents()
( $string, $status )
; status
will be AZ_OK on success:
my $string = $member->contents(); # or my ( $string, $status ) = $member->contents(); die "error $status" if $status != AZ_OK;
Can also be used to set the contents of a member (this may change the class of the member):
$member->contents( "this is my new contents" );
The Archive::Zip::FileMember class extends Archive::Zip::Member.
It is the base class for both ZipFileMember and NewFileMember classes.
This class adds an externalFileName
and an fh
member to keep
track of the external file.
externalFileName()
fh()
The Archive::Zip::ZipFileMember class represents members that have been read from external zip files.
diskNumberStart()
localHeaderRelativeOffset()
dataOffset()
Ned Konz, perl@bike-nomad.com
Copyright (c) 2000 Ned Konz. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Archive::Zip - Provide an interface to ZIP archive files. |