Perl脚本不写入解压缩的zip文件

时间:2015-04-07 19:46:48

标签: perl zipfile

我正在编写一个perl脚本,从zip文件中提取一个特定命名的文件并写入该提取的文件(除此之外还有脚本,但这是我'我陷入了困境。下面的代码是perl脚本的一部分。

我无法弄清楚为什么它没有写入文件!

my $zipName = "f:\\data\\archive.zip";
my $destPath = "f:\\data\\dataFile.DAT";
my $tempZip = Archive::Zip->new();
my $dataNum = " 0 0";

        unless ($tempZip->read($zipName) == AZ_OK ) 
        {
            die 'read error';
        }

    my @dataFileMatches = $tempZip->membersMatching( 'dataFile.*\.DAT' );

    my $dataFile;

    if($#dataFileMatches> -1)
    {
        $dataFile = $dataFileMatches[0];

        my $fileContents = $tempZip->contents($dataFile);

        my $newContents = substr $fileContents, 0, 10;
        $newContents = $newContents.$dataNum;

        my $dataFilename = $dataFile ->fileName();
        open(my $fh, '>', $dataFilename) or die "Could not open file '$dataFilename' $!";

        $tempZip->contents($dataFile, $newContents);

        $fileContents = $tempZip->contents($dataFile);

        print "New FileContents -  $fileContents\n";

        #print $fh $newContents;
        #copy($fh, $destPath);
        close $fh;
    }

以下是未执行的代码:

use strict;
use warnings;
use File::Copy qw(copy);
use Archive::Zip qw/ :ERROR_CODES :CONSTANTS /;

my $filename = 'dataFile.DAT';
open(my $fh, '>', $filename) or die "Could not open file";

print $fh "test\n";

close $fh;

但是如果我在这个提取的DAT文件所在的完全相同的目录中创建一个虚拟TEXT文件,它就可以工作。

1 个答案:

答案 0 :(得分:0)

您必须使用Archive :: Zip的extractMemberWithoutPaths()方法。

以下是如何提取文件:

#!perl

use strict;
use warnings;
use Data::Dumper qw/Dumper/;
use FindBin qw/$Bin/;
use File::Spec;
use Archive::Zip qw/AZ_OK/;

my $zipName = File::Spec->catfile($Bin, '/archive.zip');
my $destPath = File::Spec->catfile($Bin, 'dataFile.DAT');
my $tempZip = Archive::Zip->new();
my $dataNum = " 0 0";

unlink $destPath if -e $destPath;

unless ($tempZip->read($zipName) == AZ_OK ) {
    die 'read error';
}

my @dataFileMatches = $tempZip->membersMatching( {regex => 'dataFile.*\.DAT'} );

$tempZip->extractMemberWithoutPaths($dataFileMatches[0]); # extract $fileContents to current working directory

if ( -e $destPath ) {
    print "file was extracted\n";
}else{
    print "File was not extracted :(\n";
}