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

I am attempting to zip a folder (and the files within it) but not the subdirectories within it.

I have used the addTree function which works fine but also zips the subdirectories. I've also attempted the addDirectory and addFile functions neither of which I can get to work correctly. When i run my script with addDirectory i dont get any errors or warnings and the zip file is created but it is empty.

for example:
my $zip = Archive::Zip->new(); $zip->addTree( 'C:\Users\Martin\Documents\Scripts\testfolder\\' ); unless ( $zip->writeToFileNamed($BACKUPNAME) == AZ_OK ) { die 'write error'; }
Works perfectly but
my $zip = Archive::Zip->new(); $zip->addFile( 'C:\Users\Martin\Documents\Scripts\testfolder\file1.txt +' ); unless ( $zip->writeToFileNamed($BACKUPNAME) == AZ_OK ) { die 'write error'; }
or
my $zip = Archive::Zip->new(); $zip->addDirectory( 'C:\Users\Martin\Documents\Scripts\testfolder\\' ) +; unless ( $zip->writeToFileNamed($BACKUPNAME) == AZ_OK ) { die 'write error'; }
both create zip files but they are empty. Any ideas would be much appreciated. Thanks

Replies are listed 'Best First'.
Re: Problems with Archive::zip
by ahmad (Hermit) on May 18, 2010 at 14:23 UTC

    Actually you misunderstood how this module works.

    addDirectory method is not for adding an actual directory you currently have, it's just to sort things out inside your zip file

    For example:

    $zip->addDirectory('something'); $zip->writeToFileNamed('test.zip');

    Would create a zip file that contain a directory named 'something' and it doesn't to exists in your system to be added to the zip file.

    Add file should have added the file in question and I have to idea why it's failing for you ... again you can use it to sort things inside your zip file

    For example

    $zip->addDirectory('something'); $zip->addFile('C:\somefile.pl', 'something/better_name.pl'); $zip->writeToFileNamed('test.zip');

      Thanks for explaining it is a simple way, I have it working

      sub compress { #subroutine to compress the directory tree in to backup.zip in the bac +kup location print "Backing up ".$STARTLOCATION."\n"; my $zip = Archive::Zip->new(); opendir (DIR, $STARTLOCATION) or die $!; while (my $file = readdir(DIR)) { # Use -f to look for a file next unless (-f $STARTLOCATION."\\".$file); $zip->addFile($STARTLOCATION."\\".$file, $file); print "Added $file to zip\n"; } closedir(DIR); unless ( $zip->writeToFileNamed($BACKUPNAME) == AZ_OK ) { die 'write error'; } print "Successfully backed up to ". $BACKUPNAME; }