Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #217 Create a Zip archive

Create a zip-file with filename name and add the files listed in list to that zip-file.

use v5.10;
use IO::Compress::Zip qw(zip $ZipError);
my @list = ( 'file_A.txt', 'file_B.txt' );

zip \@list => 'name.zip'
    or die "zip failed: $ZipError\n";

Core module IO::Compress::Zip (available since v5.9.4) provides a zip function that takes a reference to a list (i.e. \@list not @list) and the name of the zip file. If it fails, $ZipError contains the error message. See documentation for details.
import "archive/zip"
import "bytes"
import "os"
import "io"
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
for _, filename := range list {
	input, err := os.Open(filename)
	if err != nil {
		return err
	}
	output, err := w.Create(filename)
	if err != nil {
		return err
	}
	_, err = io.Copy(output, input)
	if err != nil {
		return err
	}
}

err := w.Close()
if err != nil {
	return err
}

err = os.WriteFile(name, buf.Bytes(), 0777)
if err != nil {
	return err
}

list contains filenames of files existing in the filesystem.
In this example, the zip data is buffered in memory before writing to the filesystem.

New implementation...
< >
Bart