computing
  • 0

How to zip the file using perl

  • 0

Hi all,

I am very new for Perl, I tried to zip the file using the following script
#!perl -w

use strict;
use File::Find;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );

my $dir = ‘c:/siva’;
my $zip = Archive::Zip->new();
my $zipped;

$zipped = $zip->addDirectory( $dir );
$zipped->desiredCompressionMethod( COMPRESSION_DEFLATED );
find(&zip_file, $dir);
die ‘write error’ unless $zip->writeToFileNamed( ‘logs.zip’ ) == AZ_OK;

sub zip_file {
$zipped = $zip->addFile( $File::Find::name );
}

But i got the following errors. Could you please help me for solve this problem.

cannot call method “desiredCompressionMethod( COMPRESSION_DEFLATED )” on the undefined value at c:perlsitelibArchiveZipArchive.pm line 249

Share

1 Answer

  1. You have 2 problems.

    1) your ‘c:/siva’ dir appears to have sub dirs which will cause a problem when you attempt to $zip->addFile( $File::Find::name )

    2) when saving the file, you should supply the full path, otherwise you’ll probably end up getting this error:

    IO error: reading data : Bad file descriptor
     at C:/Perl64/lib/Archive/Zip/NewFileMember.pm line 60
    ...
    ...

    Try this version.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use File::Find;
    use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
    
    my $dir = 'c:/silva';
    my $zip = Archive::Zip->new();
    my $zipped = $zip->addDirectory( $dir );
    
    $zipped->desiredCompressionMethod( COMPRESSION_DEFLATED );
    
    find(&zip_file, $dir);
    die 'write error' unless $zip->writeToFileNamed( 'C:/logs.zip' ) == AZ_OK;
    
    sub zip_file {
        return if -d;
        $zipped = $zip->addFile( $File::Find::name );
    }

    • 0
  2. You have 2 problems.

    1) your ‘c:/siva’ dir appears to have sub dirs which will cause a problem when you attempt to $zip->addFile( $File::Find::name )

    2) when saving the file, you should supply the full path, otherwise you’ll probably end up getting this error:

    IO error: reading data : Bad file descriptor
     at C:/Perl64/lib/Archive/Zip/NewFileMember.pm line 60
    ...
    ...

    Try this version.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use File::Find;
    use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
    
    my $dir = 'c:/silva';
    my $zip = Archive::Zip->new();
    my $zipped = $zip->addDirectory( $dir );
    
    $zipped->desiredCompressionMethod( COMPRESSION_DEFLATED );
    
    find(&zip_file, $dir);
    die 'write error' unless $zip->writeToFileNamed( 'C:/logs.zip' ) == AZ_OK;
    
    sub zip_file {
        return if -d;
        $zipped = $zip->addFile( $File::Find::name );
    }

    • 0