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

I'm trying to do what I thought would be a very simple task: Create a zipfile with the contents of an entire directory, passed in to a function. I wrote (with very minor changes from the real code):

sub create_zipfile { my ($path) = @_; my $UUID = Data::GUID->new->as_string(); my $zipfile_name = $UUID . ".zip"; my $full_path = $path . "/" . $zipfile_name; my $zip = Archive::Zip->new(); $zip->addTree($path, undef); if ( ! $zip->writeToFileNamed($full_path) == AZ_OK ) { print "Error writing zipfile: $!\n"; } return $full_path; }
I tried to run this as "my $filename = create_zipfile("/path/to/directory");", and it fails with IO error: Can't open /path/to/directory/0BE30138-93B4-81EE-93CD-DC592DB8B6F0.zip for write : No such file or directory. Which--I know there's no such file or directory, I'm asking it to be created.

In a previous version of this--and I don't remember what's different, and can't replicate it--it did create a zipfile, but it was empty.

I'd be grateful for a pointer; this would seem to be the main way one would use this module, but I can't find discussion of how to do this! Thanks.

Replies are listed 'Best First'.
Re: Archive::Zip: save entire directory?
by choroba (Cardinal) on Dec 05, 2023 at 22:23 UTC
    I copied your code to a file, prepended
    #! /usr/bin/perl use warnings; use strict; use Archive::Zip qw( AZ_OK ); use Data::GUID;

    and appended

    create_zipfile('/home/choroba/_/0');

    When run, it created a zipfile in the directory, containing all the files that had existed there.

    Are you sure the path to the directory exists?

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      (OP here.)

      Aargh! Of course I checked this carefully before I posted, so when I saw your reply (and stevieb's equivalent advice), I sniffed "Yes, I'm sure the path to the directory exists!"

      Then I checked more carefully, and realized that I'd been passing in a relative path from my main directory that wasn't the same as the relative path from the test directory where I was actually running the script....

      I'm sorry to have wasted everyone's time with something so obvious. I actually tried to rubber-duck it first! sigh I guess I'm glad my code was OK, I just didn't know how to run it :-(

        I'm sorry to have wasted everyone's time with something so obvious

        It's not a waste of anyone's time...we all make mistakes that seem silly when we solve the issue. It's part of being human. And seeing your mistake helps others avoid it in the future!

Re: Archive::Zip: save entire directory?
by stevieb (Canon) on Dec 05, 2023 at 22:19 UTC

    Does the entire directory path exist? The software can only create the file, it will fail if the full directory path doesn't exist yet.