Question

I want to uncompress zipped file say, files.zip, to a directory that is different from my working directory. Say, my working directory is /home/user/address and I want to unzip files in /home/user/name.

I am trying to do it as follows

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

my $files= "/home/user/name/files.zip"; #location of zip file
my $wd = "/home/user/address" #working directory
my $newdir= "/home/user/name"; #directory where files need to be extracted
my $dir = `cd $newdir`;
my @result = `unzip $files`; 

But when run the above from my working directory, all the files get unzipped in working directory. How do I redirect the uncompressed files to $newdir?

Was it helpful?

Solution

unzip $files -d $newdir

OTHER TIPS

Use Perl command

chdir $newdir;

and not the backticks

`cd $newdir`

which will just start a new shell, change the directory in that shell, and then exit.

Though for this example, the -d option to unzip is probably the simplest way to do what you want (as mentioned by ennuikiller), for other types of directory-changing, I like the File::chdir module, which allows you to localize directory changes, when combined with the perl "local" operator:

#!/usr/bin/perl
use strict;
use warnings;
use File::chdir;

my $files= "/home/user/name/files.zip"; #location of zip file
my $wd = "/home/user/address" #working directory
my $newdir= "/home/user/name"; #directory where files need to be extracted
# doesn't work, since cd is inside a subshell:   my $dir = `cd $newdir`;
{ 
   local $CWD = $newdir;
   # Within this block, the current working directory is $newdir
   my @result = `unzip $files`;
}
# here the current working directory is back to what it was before

You can also use the Archive::Zip module. Look specifically at the extractToFileNamed:

"extractToFileNamed( $fileName )

Extract me to a file with the given name. The file will be created with default modes. Directories will be created as needed. The $fileName argument should be a valid file name on your file system. Returns AZ_OK on success. "

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top