in reply to Multiple zip files from directories!

The first thing that occurs to me is to add files until you are about to pass 5 MB, and then start a new archive. Perhaps something like (untested):
#!/usr/bin/perl -w use strict; use Archive::Zip qw/AZ_OK/; use File::Temp qw/tempfile/; use constant MB => 1024 * 1024; my $dir = qw( zip_this/); my @files = do { opendir my $fd, "$dir" or die $! or die $!; grep -f, map "$dir$_", readdir $fd; }; my $zip = Archive::Zip->new; my $total = 0; my $limit = 5*MB; my $FileCount = 0; my $archiveCount = 0; foreach my $file (@files) { my $temp = Archive::Zip->new; my $member = $temp->addFile($file); next unless $member->compressedSize; my $fh = tempfile(); $temp->writeToFileHandle($fh) == AZ_OK or die $!; if ($total + $member->compressedSize > $limit) { $zip->writeToFileNamed("zipped_$archiveCount.zip") == AZ_OK or + die $!; $archiveCount++; print "Total archive size: $total bytes\n\n"; $total = 0; $zip = Archive::Zip->new; } $zip->addMember($member); $total += $member->compressedSize; } print "Total archive size: $total bytes\n"; $zip->writeToFileNamed("zipped_$archiveCount.zip") == AZ_OK or die $!;
Update: Fixed copy/paste scoping bug; see Re^3: Multiple zip files from directories! for information. Also initialized $total as per Anonymous Monk's suggestion below.

Replies are listed 'Best First'.
Re^2: Multiple zip files from directories!
by Anonymous Monk on Sep 15, 2011 at 15:24 UTC
    This is a great, maybe initialize the variable $total as $total=0; to avoid this:
    Use of uninitialized value $total in addition (+) at test.pl line 34.
Re^2: Multiple zip files from directories!
by Anonymous Monk on Sep 15, 2011 at 19:39 UTC
    It is making sense now, have one question if you could on this part of the code:
    ... if ($total + $member->compressedSize > $limit) { $zip->writeToFileNamed("zipped_$archiveCount.zip") == AZ_OK or + die $!; $archiveCount++; print "Total archive size: $total bytes\n\n"; $total = 0; my $zip = Archive::Zip->new; } $zip->addMember($member); # <---- This line ...
    the last line here where the files are added to the zip file(s), I tried this: $zip->addMember($member) unless $zip->addMember($member); to avoid duplicated files inside of the zip files. But what is happening is that the zip files are been created, that is good, but the files inside of the zip are been added repeatedly. I just need to prevent this somehow. Any suggestions?
      Like I said, untested. The line my $zip = Archive::Zip->new; should have read $zip = Archive::Zip->new;. Rather than creating a new archive in the variable $zip, I was creating a new archive and storing it in a new $zip variable that went out of scope immediately,; hence I kept adding to the old archive. The corrected, functional version is posted in an updated Re: Multiple zip files from directories!