📄 zip.pm
字号:
Returns the name of the file last read from. If nothing hasbeen read yet, returns an empty string; if read from a filehandle, returns the handle in string form.=back=head2 Zip Archive Member OperationsVarious operations on a zip file modify members. When a member ispassed as an argument, you can either use a reference to the memberitself, or the name of a member. Of course, using the name requiresthat names be unique within a zip (this is not enforced).=over 4=item removeMember( $memberOrName )Remove and return the given member, or match its name andremove it. Returns undef if member or name doesn't exist in thisZip. No-op if member does not belong to this zip.=item replaceMember( $memberOrName, $newMember )Remove and return the given member, or match its name andremove it. Replace with new member. Returns undef if member orname doesn't exist in this Zip, or if C<$newMember> is undefined.It is an (undiagnosed) error to provide a C<$newMember> that is amember of the zip being modified. 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.=item extractMember( $memberOrName [, $extractedName ] )Extract the given member, or match its name and extract it.Returns undef if member doesn't exist in this Zip. Ifoptional second arg is given, use it as the name of theextracted member. Otherwise, the internal filename of themember is used as the name of the extracted file ordirectory.If you pass C<$extractedName>, it should be in the local filesystem's format.All necessary directories will be created. Returns C<AZ_OK>on success.=item extractMemberWithoutPaths( $memberOrName [, $extractedName ] )Extract the given member, or match its name and extract it.Does not use path information (extracts into the currentdirectory). Returns undef if member doesn't exist in thisZip.If optional second arg is given, use it as the name of theextracted member (its paths will be deleted too). Otherwise,the internal filename of the member (minus paths) is used asthe name of the extracted file or directory. Returns C<AZ_OK>on success.=item addMember( $member )Append a member (possibly from another zip file) to the zipfile. Returns the new member. Generally, you will useaddFile(), addDirectory(), addFileOrDirectory(), addString(),or read() to add members. # Move member named 'abc' to end of zip: my $member = $zip->removeMember( 'abc' ); $zip->addMember( $member );=item updateMember( $memberOrName, $fileName )Update a single member from the file or directory named C<$fileName>.Returns the (possibly added or updated) member, if any; C<undef> onerrors.The comparison is based on C<lastModTime()> and (in the case of anon-directory) the size of the file.=item addFile( $fileName [, $newName ] )Append a member whose data comes from an external file,returning the member or undef. The member will have its filename set to the name of the external file, and itsdesiredCompressionMethod set to COMPRESSION_DEFLATED. Thefile attributes and last modification time will be set fromthe file.If the name given does not represent a readable plain file orsymbolic link, undef will be returned. C<$fileName> must bein the format required for the local file system.The optional C<$newName> argument sets the internal file nameto something different than the given $fileName. C<$newName>,if given, must be in Zip name format (i.e. Unix).The text mode bit will be set if the contents appears to betext (as returned by the C<-T> perl operator).I<NOTE> that you shouldn't (generally) use absolute path namesin zip member names, as this will cause problems with some ziptools as well as introduce a security hole and make the zipharder to use.=item addDirectory( $directoryName [, $fileName ] )Append a member created from the given directory name. Thedirectory name does not have to name an existing directory.If the named directory exists, the file modification time andpermissions are set from the existing directory, otherwisethey are set to now and permissive default permissions.C<$directoryName> must be in local file system format.The optional second argument sets the name of the archivemember (which defaults to C<$directoryName>). If given, itmust be in Zip (Unix) format.Returns the new member.=item addFileOrDirectory( $name [, $newName ] )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.C<$name> must be in local file system format.The optional second argument sets the name of the archivemember (which defaults to C<$name>). If given, it must be inZip (Unix) format.=item addString( $stringOrStringRef, $name )Append a member created from the given string or stringreference. The name is given by the second argument.Returns the new member. The last modification time will beset to now, and the file attributes will be set to permissivedefaults. my $member = $zip->addString( 'This is a test', 'test.txt' );=item contents( $memberOrMemberName [, $newContents ] )Returns the uncompressed data for a particular member, orundef. 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 includethe status as the second value in the array. ($content, $status) = $zip->contents( 'xyz.txt');=back=head2 Zip Archive I/O operationsA Zip archive can be written to a file or file handle, or read fromone.=over 4=item writeToFileNamed( $fileName )Write a zip archive to named file. Returns C<AZ_OK> onsuccess. 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 filethat you read in, you will clobber ZipFileMembers. Soinstead, write to a different file name, then delete theoriginal.If you use the C<overwrite()> or C<overwriteAs()> methods, you canre-write the original zip in this way.C<$fileName> should be a valid file name on your system.=item writeToFileHandle( $fileHandle [, $seekable] )Write a zip archive to a file handle. Return AZ_OK onsuccess. The optional second arg tells whether or not to tryto seek backwards to re-write headers. If not provided, it isset if the Perl C<-f> test returns true. This could fail onsome 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 ifyou're writing to a pipe or a socket), pass a false secondargument: my $fh = IO::File->new( '| cat > somefile.zip', 'w' ); $zip->writeToFileHandle( $fh, 0 ); # fh is not seekableIf this method fails during the write of a member, thatmember and all following it will return false fromC<wasWritten()>. See writeCentralDirectory() for a way todeal with this.If you want, you can write data to the file handle beforepassing it to writeToFileHandle(); this could be used (forinstance) for making self-extracting archives. However, thisonly works reliably when writing to a real file (as opposedto STDOUT or some other possible non-file).See examples/selfex.pl for how to write a self-extractingarchive.=item writeCentralDirectory( $fileHandle [, $offset ] )Writes the central directory structure to the given filehandle.Returns AZ_OK on success. If given an $offset, willseek to that point before writing. This can be used forrecovery in cases where writeToFileHandle or writeToFileNamedreturns an IO error because of running out of space on thedestination file.You can truncate the zip by seeking backwards and then writing thedirectory: 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()); } }=item overwriteAs( $newName )Write the zip to the specified file, as safely as possible.This is done by first writing to a temp file, then renamingthe original if it exists, then renaming the temp file, thendeleting the renamed original if it exists. Returns AZ_OK ifsuccessful.=item overwrite()Write back to the original zip file. See overwriteAs() above.If the zip was not ever read from a file, this generates anerror.=item read( $fileName )Read zipfile headers from a zip file, appending new members.Returns C<AZ_OK> or error code. my $zipFile = Archive::Zip->new(); my $status = $zipFile->read( '/some/FileName.zip' );=item readFromFileHandle( $fileHandle, $filename )Read zipfile headers from an already-opened file handle,appending new members. Does not close the file handle.Returns C<AZ_OK> or error code. Note that this requires aseekable file handle; reading from a stream is not yetsupported. 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 );=back=head2 Zip Archive Tree operationsThese used to be in Archive::Zip::Tree but got moved intoArchive::Zip. They enable operation on an entire tree of members orfiles.A usage example: 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' );=over 4=item $zip->addTree( $root, $dest [,$pred] ) -- Add tree of files to a zipC<$root> is the root of the tree of files and directories to beadded. It is a valid directory name on your system. C<$dest> isthe name for the root in the zip file (undef or blank meansto use relative pathnames). It is a valid ZIP directory name(that is, it uses forward slashes (/) for separatingdirectory components). C<$pred> is an optional subroutinereference to select files: it is passed the name of theprospective file or directory using C<$_>, and if it returnstrue, the file or directory will be included. The default isto add all readable files and directories. For instance,using my $pred = sub { /\.txt/ }; $zip->addTree( '.', '', $pred );will add all the .txt files in and below the currentdirectory, using relative names, and making the namesidentical in the zipfile: original name zip member name ./xyz xyz ./a/ a/ ./a/b a/bTo translate absolute to relative pathnames, just pass themin: $zip->addTree( '/c/d', 'a' ); original name zip member name /c/d/xyz a/xyz /c/d/a/ a/a/ /c/d/a/b a/a/bReturns AZ_OK on success. Note that this will not followsymbolic links to directories. Note also that this does notcheck for the validity of filenames.Note that you generally I<don't> want to make zip archive member namesabsolute.=item $zip->addTreeMatching( $root, $dest, $pattern [,$pred] )$root is the root of the tree of files and directories to beadded $dest is the name for the root in the zip file (undefmeans to use relative pathnames) $pattern is a (non-anchored)regular expression for filenames to match $pred is anoptional subroutine reference to select files: it is passedthe name of the prospective file or directory in C<$_>, andif it returns true, the file or directory will be included.The default is to add all readable files and directories. Toadd all files in and below the current dirctory whose namesend in C<.pl>, and make them extract into a subdirectorynamed C<xyz>, do this: $zip->addTreeMatching( '.', 'xyz', '\.pl$' )To add all I<writable> files in and below the dirctory namedC</abc> whose names end in C<.pl>, and make them extract intoa subdirectory named C<xyz>, do this: $zip->addTreeMatching( '/abc', 'xyz', '\.pl$', sub { -w } )Returns AZ_OK on success. Note that this will not followsymbolic links to directories.=item $zip->updateTree( $root, [ $dest, [ $pred [, $mirror]]] );Update a zip file from a directory tree.C<updateTree()> takes the same arguments as C<addTree()>, but firstchecks to see whether the file or directory already exists in the zipfile, and whether it has been changed.If the fourth argument C<$mirror> is true, then delete all my membersif corresponding files weren't found.Returns an error code or AZ_OK if all is well.=item $zip->extractTree()=item $zip->extractTree( $root )=item $zip->extractTree( $root, $dest )=item $zip->extractTree( $root, $dest, $volume )If you don't give any arguments at all, will extract all thefiles in the zip with their original names.If you supply one argument for C<$root>, C<extractTree> will extractall the members whose names start with C<$root> into the currentdirectory, stripping off C<$root> first.C<$root> is in Zip (Unix) format.For instance, $zip->extractTree( 'a' );when applied to a zip containing the files:a/x a/b/c ax/d/e d/e will extract:a/x as ./xa/b/c as ./b/cIf you give two arguments, C<extractTree> extracts all the memberswhose names start with C<$root>. It will translate C<$root> intoC<$dest> to construct the destination file name.C<$root> and C<$dest> are in Zip (Unix) format.For instance, $zip->extractTree( 'a', 'd/e' );when applied to a zip containing the files:a/x a/b/c ax/d/e d/e will extract:a/x to d/e/xa/b/c to d/e/b/c and ignore ax/d/e and d/eIf you give three arguments, C<extractTree> extracts all the memberswhose names start with C<$root>. It will translate C<$root> intoC<$dest> to construct the destination file name, and then it willconvert to local file system format, using C<$volume> as the name ofthe destination volume.C<$root> and C<$dest> are in Zip (Unix) format.C<$volume> is in local file system format.For instance, under Windows, $zip->extractTree( 'a', 'd/e', 'f:' );when applied to a zip containing the files:a/x a/b/c ax/d/e d/e will extract:a/x to f:d/e/xa/b/c to f:d/e/b/c and ignore ax/d/e and d/eIf you want absolute paths (the prior example used paths relative tothe current directory on the destination volume, you can specify thesein C<$dest>: $zip->extractTree( 'a', '/d/e', 'f:' );when applied to a zip containing the files:a/x a/b/c ax/d/e d/e will extract:a/x to f:\d\e\xa/b/c to f:\d\e\b\c and ignore ax/d/e and d/eReturns an error code or AZ_OK if everything worked OK.=back=head1 MEMBER OPERATIONS=head2 Member Class MethodsSeveral constructors allow you to construct members without addingthem to a zip archive. These work the same as the addFile(),
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -