Smartelf
Smartelf

Reputation: 879

Adding a member to zip file from a file handle in Perl

I am trying to add a remote file to a local zip archive. Currently, I am doing something like this.

use Modern::Perl;
use Archive::Zip;
use File::Remote;

my $remote = File::Remote->new(rsh => "/usr/bin/ssh", rcp => "/usr/bin/scp");
my $zip = Archive::Zip->new();

$remote->open(*FH,'host2:/file/to/add.txt');
my $fh = IO::File->new_from_fd(*FH,'r');

#this is what I want to do.
$zip->addFileHandle($fh,'add.txt');

...

Unfortunately, Archive::Zip does not have have an addFileHandle method.

Is there another way that I can do that?

Thanks.

Upvotes: 1

Views: 586

Answers (2)

pmqs
pmqs

Reputation: 3705

Archive::Zip might not have filehandle support for writing to a zip file, but Archive::Zip::SimpleZip does.

Here is a self-contained example that shows how to read from a filehandle & write directly to the zip file without any need for a temporary file.

use warnings;
use strict;

use Archive::Zip::SimpleZip;
use File::Remote;

# create a file to add to the zip archive
system "echo hello world >/tmp/hello" ;

my $remote = File::Remote->new(rsh => "/usr/bin/ssh", rcp => "/usr/bin/scp");
my $zip = Archive::Zip::SimpleZip->new("/tmp/r.zip");

$remote->open(*FH,'/tmp/hello');

# Create a filehandle to write to the zip fiule.
my $member = $zip->openMember(Name => 'add.txt');

my $buffer;
while (read(FH, $buffer, 1024*16))
{
    print $member $buffer ;
}

$member->close();
$zip->close();

# dump the contents of the zipo file to stdout
system "unzip -p /tmp/r.zip" ;    

Upvotes: 1

Miguel Prz
Miguel Prz

Reputation: 13792

Do something like this (copy to local path):

$remote->copy("host:/remote/file", "/local/file");

and use the addFile method provided by Archive::Zip with the local file

Upvotes: 2

Related Questions