Archive tar files to a different location inperl
        Posted  
        
            by user314261
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by user314261
        
        
        
        Published on 2010-04-12T06:33:53Z
        Indexed on 
            2010/04/12
            6:43 UTC
        
        
        Read the original article
        Hit count: 246
        
Hi,
I am a newbee in Perl.
I am reading a directory having some archive files and uncompressing the archive files one by one.
Everything seems well however the files are getting uncompressed in the folder which has the main perl code module which is running the sub modules.
I want the archive to be generated in the folder I specify.
This is my code:
sub ExtractFile
{
 #Read the folder which was copied in the output path recursively and extract if any file is compressed
 my $dirpath = $_[0];
 opendir(D, "$dirpath") || die "Can't open dir $dirpath: $!\n";
 my @list = readdir(D);
 closedir(D);
 foreach my $f (@list) 
 {
  print " \$f = $f";
  if(-f $dirpath."/$f")
  {
   #print " File in  directory $dirpath \n ";#is \$f = $f\n";
   my($file_name, $file_dirname,$filetype)= fileparse($f,qr{\..*});
   #print " \nThe file extension is $filetype";
   #print " \nThe file name is is $file_name";
   # If compressed file then extract the file
   if($filetype eq ".tar" or $filetype eq ".tzr.gz")
   {
    my $arch_file = $dirpath."/$f";
    print "\n file to be extracted is $arch_file";
    my $tar = Archive::Tar->new($arch_file);
    #$tar->extract() or die ("Cannot extract file $arch_file");
    #mkdir($dirpath."/$file_name");
    $tar->extract_file($arch_file,$dirpath."/$file_name" ) or die ("Cannot extract file $arch_file");
   }
  }
  if(-d $dirpath."/$f")
  {
   if($f eq "." or $f eq "..")
   { next; }
   print " Directory\n";# is $f";
   ExtractFile($dirpath."/$f");
  }
 }
}
The method ExtractFile is called recursively to loop all the archives. When using $tar->extract() it uncompresses in the folder which calls this metohd.
when I use $tar->extract_file($arch_file,$dirpath."/$file_name" ) I get an error :
No such file in archive: '/home/fsang/dante/workspace/output/s.tar' at /home/fsang/dante/lib/Extraction.pm line 80
Please help I have checked that path and input output there is no issue with it.
Seems some usage problem I am not aware of for $tar->extract_file().
Many thanks for anyone resolving this issue.
Regards, Sakshi
© Stack Overflow or respective owner