开发者

How can I list the contents of a ZIP file using Perl?

开发者 https://www.devze.com 2023-03-26 22:06 出处:网络
What I am aiming to do is pretty much what it says in the title. I have the following line of code which simply prints out [view archive] and when I click it the browser just downloads the zip file.

What I am aiming to do is pretty much what it says in the title.

I have the following line of code which simply prints out [view archive] and when I click it the browser just downloads the zip file.

print "\<a href=\"http:\/\/intranet.domain.com\/~devcvs\/view-file.cgi?file=$reviewdata{'document'}&review_id=$reviewdata{'id'}\"\>[view archive]\<\/a\>\n";

What I would love to do is to list the files contained within this zip file anywhere on the page, e.g. just underneath or even a new page which this link links to and takes the filename as a parameter.

I believe once this is done the browser should take care of the rest in terms of just clicking these files and viewing the开发者_C百科m in the browser as they will be pdfs and html files which I don't foresee any problems with.

I am sure there is a module that does this but I am unsure of how to accomplish my goal using it.

Any help is much appreciated.


Have a look at Archive::Zip :

use strict;
use warnings;

use Archive::Zip qw/ :ERROR_CODES :CONSTANTS /;

my $zipFile = 'someZip.zip';

my $zip = Archive::Zip->new();

unless ( $zip->read( $zipFile ) == AZ_OK ) {  # Make sure archive got read

    die 'read error';
}

my @files = $zip->memberNames();  # Lists all members in archive

print $_, "\n" for @files;


Using Archive::Zip certainly makes the code easier, and you should probably install that module if you are going to work extensively on zip files.

However, for those who prefer not to install anything, there is a way to list the content of a zip file just using the core module IO::Uncompress::Unzip (already part of any standard Perl distribution).

use strict;
use warnings;

use IO::Uncompress::Unzip qw($UnzipError);

my $zipFile = '/path/to/zipfile.zip';

my $u = IO::Uncompress::Unzip->new($zipFile)
    or die "Error: $UnzipError\n";

my $status;
for ($status = 1; $status > 0; $status = $u->nextStream()) {
    my $header = $u->getHeaderInfo();
    my $zippedFile = $header->{Name};
    if ($zippedFile =~ /\/$/) {
        last if $status < 0;
        next;
    }
    print "$zippedFile\n";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消