in reply to Archive::Zip Simple Issue

By putting "my $zip = Archive::Zip->new();" inside the loop, you're creating a new archive for each file. You need to create one archive, outside of the loop, then loop over the files, adding each one to the archive.

Replies are listed 'Best First'.
Re^2: Archive::Zip Simple Issue
by drodinthe559 (Monk) on May 29, 2009 at 21:26 UTC
    I tried putting it outside and it seems to get that same error message. I creates each zip file, but the zip file is empty.
    #!/usr/bin/perl -w use strict; use warnings; use File::Basename; use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); my $procdate = sprintf "%02d%02d%02d%02d%02d%02d", (localtime)[4]+1, ( +localtime)[3], substr((localtime)[5]+1900,2,2),(localtime)[2], (local +time)[1], (localtime)[0]; my @dipfile = glob('C:/ReportExtract/Director/*.xml'); ##### Zip each file into a zip file for archiving ##### my $targetdir = File::Spec->catdir('C:/ReportExtract/Director/'); my $targetzip = File::Spec->catdir($targetdir, basename($procdate) . " +.zip"); #Need basename. my $zip = Archive::Zip->new(); my $zipdir = $zip->addDirectory($targetdir); foreach my $xml_file (@dipfile) { my $temp = File::Basename::fileparse($xml_file); #Trying it with o +nly the basename. $zipdir = $zip->addFile($temp); }; unless ( $zip->writeToFileNamed($targetzip) eq "AZ_OK" ) {die 'rea +d error';}
    Here is the updated code. Dave

      I think $zip->addFile() needs the complete path, not just the filename. So try this:

      # outside of loop: $dir = "C:/ReportExtract/Director"; # ... # inside your foreach loop: if (-e "$dir/$temp" ) { unless ( $zip->addFile("$dir/$temp") ) { print "Error: failed to add $dir/$temp to archive.\n"; } } else { print "Error: $dir/$temp does not exist!\n"; }

      This also adds error checking, so you can see if it's doing the right thing as it runs.