Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Perl script to unzip files

A Perl script that will unzip files by extracting contents and saving them to a new directory named after the source zip file.

The following Perl script can be used to unzip files. The script relies on Archive::Zip (which will need to be installed) and File::Basename (which comes with Perl).

To activate, open cmd and enter perl \path\to\TidyUnzipper.pl \path\to\file.zip.

#!/usr/bin/perl
use strict;
use warnings;

package TidyUnzipper;

use strict;
use Archive::Zip qw(:ERROR_CODES :CONSTANTS);
use Exporter 'import';

our @EXPORT = qw(unzip);

# For Command-Line Options
my ($zip_file, $out_file, $filter) = @ARGV;
unzip($zip_file, $out_file, $filter) if scalar @ARGV;

1;

# Make file name string
my $shortname = fileparse($zip_file, qr/\Q.zip\E/);

# Unzip file into a new directory called zip_temp
sub Unzipper {
	my ($zip_file, $out_file, $filter) = @_;
	my $zip = Archive::Zip->new();
	unless ( $zip->read( $zip_file ) == AZ_OK ) { 
		die 'Read error: The file could not be unzipped';
	}
  $zip->extractTree( '', 'zip_temp/' );	
}

# Rename zip_temp
	rename("zip_temp", $shortname);

# Explanation
use File::Basename;
use strict;

	# Get full path in $path
	my $filename = basename($zip_file);

	# Print statement
print "The file $filename has been unzipped.\n";

This code has been published on GitHub Gist and is loosely based on ZipUtil.pm.

   

Comments

2 responses to “Perl script to unzip files”

On 6 February 2020, satyam dixit wrote: Hyperlink chain icon

if i have to do this without using “use Archive::Zip” module , than what should i do?

Reply

On 23 September 2023, fred flintstone wrote: Hyperlink chain icon

unzip $files -d $newdir

Reply

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.