Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have been trying to zip a directory and that directory contains files and sub directories and the sub directories might or not contain more files or directories. I was trying to do this in windows using Archive::zip. But I am not able to, Can any body suggest some tips of how to accomplish this? Thanks and Regards, Sid

Replies are listed 'Best First'.
Re: How to zip directory on windows
by spiritway (Vicar) on Mar 08, 2006 at 08:39 UTC

    I'm not sure what you mean when you say you're "not able to" zip your desired directories. In the documentation for Archive::Zip, there is a description of tree operations. The example they give is:

    use Archive::Zip; my $zip = Archive::Zip->new(); # add all readable files and directories below . as xyz/* $zip->addTree( '.', 'xyz' ); # add all readable plain files below /abc as def/* $zip->addTree( '/abc', 'def', sub { -f && -r } ); # add all .c files below /tmp as stuff/* $zip->addTreeMatching( '/tmp', 'stuff', '\.c$' ); # add all .o files below /tmp as stuff/* if they aren't writable $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { ! -w } ); # add all .so files below /tmp that are smaller than 200 bytes as stuf +f/* $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { -s < 200 } ); # and write them into a file $zip->writeToFileNamed('xxx.zip'); # now extract the same files into /tmpx $zip->extractTree( 'stuff', '/tmpx' );

    This should help you to get started. Note that this module uses the Unix format for path names (forward slashes), even in Windows.

      Here's a useful example of how to zip a Windows directory and all subdirectories and gif files, while keeping the original directory structure:
      #!/usr/bin/perl use strict; use warnings; use Archive::Zip qw/ :ERROR_CODES :CONSTANTS/; my $maindir = 'C:\StuffToZip'; my $zipfile = 'backup.zip'; my $zip = Archive::Zip->new(); opendir(MAINDIR, $maindir) or die "Can't open $maindir: $!"; my @folders = readdir(MAINDIR); foreach (@folders) { next if $_ =~ /^\./; if (-d "$maindir\\$_") { &zip("$_", "$maindir\\$_"); } else { print "Error reading $maindir\\$_\n"; } } $zip->writeToFileNamed($zipfile) == AZ_OK or die "Can't write >$zipfil +e<: $!\n"; closedir MAINDIR; sub zip { my $type = shift; my $dir = shift; #Adds all subdirectories under $maindir and any gif files found $zip->addTreeMatching( "$dir", "$type", '\.gif$' ); }
      Hope it helps. Cheers