分类: Python/Ruby
2012-08-31 16:50:16
Perl可以通过Archive::Zip模块,动态建立和阅读ZIP压缩文件,而不必依赖外来工具和实用工具。
首先安装该模块,比较耗时间,
cpan Archive::Zip
1,建立ZIP压缩文件
脚本如下:
#!/usr/bin/perl
use strict;
use warnings;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
my $zip = Archive::Zip->new();
# establish zip file.
my @files = (
'/home/sysadmin/aaa/dns.pl',
'/home/sysadmin/aaa/md5.pl',
'/home/sysadmin/aaa/apache.pl'
);
foreach my $file (@files) {
$zip->addFile($file);
}
unless ( $zip->writeToFileNamed('/opt/zip.zip') == AZ_OK ) {
print "Error in archive creation!\n";
}
else {
print "Archive created successfully!\n";
}
2,查看ZIP压缩文件内容
脚本如下:
#!/usr/bin/perl
use strict;
use warnings;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
my $zip = Archive::Zip->new();
# read zip file.
my $status = $zip->read("/opt/zip.zip");
if ( $status != AZ_OK ) {
die('Error in file!');
}
else {
foreach my $member ( $zip->members() ) {
print $member->fileName(), ", ", $member->uncompressedSize(), ":",
$member->compressedSize(), "\n";
}
}
3,在现有ZIP压缩文件中插入文件
脚本如下:
# read zip file.
my $status = $zip->read("/opt/zip.zip");
if ( $status != AZ_OK ) {
die('Error in file!');
}
else {
my @files = (
'/home/sysadmin/chentao/apache.pl'
);
foreach my $file (@files) {
$zip->addFile($file);
}
if ( $zip->overwrite() != AZ_OK ) {
print "Error in archive creation!";
}
else {
print "Archive created successfully!";
}
}
在一个现有压缩文件中插入一个文件的过程与建立一个新压缩文件非常相似,成功添加文件后,就可以用overwrite()方法用更新后的压缩文件覆盖原始的压缩文件。