在Perl中将tar文件归档到不同的位置

在Perl中将tar文件归档到不同的位置,perl,file,extract,Perl,File,Extract,我正在读取一个目录,其中包含一些存档文件,并逐个解压缩存档文件 一切似乎都很好,但是文件在文件夹中被解压,文件夹中有运行子模块的主perl代码模块 我希望在指定的文件夹中生成存档文件 这是我的代码: sub ExtractFile { #Read the folder which was copied in the output path recursively and extract if any file is compressed my $dirpath = $_[0]; ope

我正在读取一个目录,其中包含一些存档文件,并逐个解压缩存档文件

一切似乎都很好,但是文件在文件夹中被解压,文件夹中有运行子模块的主perl代码模块

我希望在指定的文件夹中生成存档文件

这是我的代码:

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");
  }

 }


}
递归调用ExtractFile方法以循环所有存档。 使用
$tar->extract()
时,它会在调用此方法的文件夹中解压缩

当我使用
$tar->extract\u file($arch\u file,$dirpath./$file\u name”)
时,我得到一个错误:

存档文件中没有此类文件:“/home/fsang/dante/workspace/output/s.tar”位于/home/fsang/dante/lib/Extraction.pm第80行

请帮助我检查路径和输入输出,它没有问题

对于
$tar->extract\u file()
,似乎存在一些我不知道的使用问题

非常感谢所有解决此问题的人

问候,, 萨基是打字错误吗

$tar->extract_file($arch_file,$dirpath."/$file_name" ) 
应该是

$tar->extract_file($arch_file,$dirpath."/".$file_name) 

您误解了
提取文件
。第一个参数是要提取的归档文件中的文件名。您正在传递存档本身的路径。您将其传递给了
new
;你不必再传了。正如错误消息所解释的,
s.tar
不包含名为
/home/fsang/dante/workspace/output/s.tar
的文件,因此
提取文件
失败

您可以使用
$tar->list\u files
获取归档文件中的文件列表


一个更简单的解决方案可能是临时chdir到要将归档文件解压缩到的目录。提供了一种简单的方法。

我看到一支枪被带到瑞士军刀战中。
$tarFile = "test.tar.gz";
$myTar = Archive::Tar->new($tarFile);
foreach my $member ($myTar->list_files())
{
    my $res = $myTar->extract_file( $member , 'C:/temp/'.$member );
    print "Exract error!\n" unless ($res);
}
这里有一个*nix one liner,可以满足您的需求:

find /source/dir -name "*.tar" -exec tar -C /target/dir -xvzf '{}' \; -print
是否需要为此编写脚本?
除了调试行之外,您不必做任何特殊的事情

不,是你错了。您的“固定”行中有奇数个引号。谢谢@cjm-我忘记了行末的引号-编辑这两行完全相等。Perl在双引号字符串上执行变量插值。您能解释一下在第一个参数中要传递什么吗?我也传递了存档文件的名称,即s.tar,但它仍然表示存档文件中没有这样的文件:包含一个名为/home/fsang/dante/workspace/output/s.tar的文件似乎正在某个集合中搜索该文件,调用extract_file方法之前是否需要将其添加到某个集合属性中谢谢您的帮助Hi谢谢。。现在我更好地理解了它,并使用File::pushd找到了解决方案非常感谢