LoginSignup
1
0

More than 3 years have passed since last update.

IO::Compress::Zipでzipファイルを作る

Last updated at Posted at 2019-12-09

Perl Advent Calendar 2019 の10日目です!!
昨日はskajiさんでした。


この間、IO::Compress::Zipで、zipファイルを作成したのですが、記事が少なそうでしたので、簡単な使い方紹介をしようと思います。

IO::Compress::Zipとは

IO::Compress::Zip - Write zip files/buffers

IO::Compress::Zipはfileやbufferからzip fileを書き出してくれる君です。

実行環境

MacBook Pro
OS: macOS Mojave
Perl v5.28.2

使い方

zip fileを開いて、zipを作る。

IO::Compress::Zipの第一引数にpath、もしくはfilehandleを渡すと、そのファイルを開いて、zipファイルを作ってくれます。
ちなみに、渡したfilehandleは、IO::Compress::Zipのclose時に、内部でcloseしてくれるようです。

use strict;
use warnings;

use IO::Compress::Zip qw/$ZipError/;

my $out = 'test.zip';
my $z = IO::Compress::Zip->new($out, NAME => 'test.text') or die "zip failed: $ZipError\n";
$z->write("hello zip\n");
$z->write("hello perl\n");

$z->close();

もしくは、

use strict;
use warnings;

use IO::Compress::Zip qw/$ZipError/;

my $out = 'test.zip';
my $fh;
open($fh, ">", $out) or die("error :$!");

my $z = IO::Compress::Zip->new($fh, NAME => 'test.text') or die "gzip failed: $ZipError\n";
$z->write("hello zip\n");
$z->write("hello perl\n");

$z->close();
$ perl test_zip_file.pl
$ unzip -l test.zip
Archive:  test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       21  12-04-2019 14:36   test.text
---------                     -------
       21                     1 file

bufferにzipを作る。

IO::Compress::Zipにscalarのリファレンスを渡すと、そこに書き込んでくれます。

use strict;
use warnings;

use IO::Compress::Zip qw/$ZipError/;

my $out = '';
my $z = IO::Compress::Zip->new(\$out, NAME => 'test.text') or die "zip failed: $ZipError\n";;
$z->write("hello zip\n");
$z->write("hello perl\n");
$z->close();

print $z;

my $fh;
open($fh, ">", "data.zip") or die("error :$!");
print $fh $out;
close $fh;

bufferに作成したzipファイルは、そのままfileに出力することができます。

$ perl test_zip_file.pl
IO::Compress::Zip=GLOB(0x7fcf48005908)
$ unzip -l data.zip
Archive:  data.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       21  12-06-2019 16:34   test.text
---------                     -------
       21                     1 file

ちょっとハマったこと

zipファイルを作る際、NAME option(NAME => 'test.text') を入れてあげないと、unzipできなくなるので注意が必要です。
https://metacpan.org/pod/IO::Compress::Zip#Name-=%3E-$string
https://stackoverflow.com/questions/55043193/zip-archive-contain-files-without-names-how-to-unzip-it

$ unzip -l test.zip
Archive:  test.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       21  12-04-2019 14:41
---------                     -------
       21                     1 file

$ unzip test.zip
Archive:  test.zip
mapname:  conversion of  failed

以上になります。

明日は、codehexさんです。
良いクリスマスを!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0