Perl tar 文件递归创建目录



我正在使用Archive::Tar模块来获取目录内容。

我的脚本如下:

#!/usr/bin/perl -w 
use strict;
use warnings;
use Archive::Tar;
use File::Find;
use Data::Dumper;
my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";
my $src_location = $home_dir."LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";
my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $src_location);
print "Files:".Dumper(@inventory);
my $tar = Archive::Tar->new();
$tar->add_files( @inventory );
$tar->write( $dst_location , 9 );

脚本能够在位置C:/Users/Documents/Vinod/Perl_Scripts/test/中创建file.tar.gz文件。

但是当我手动提取file.tar.gz时,它会再次递归地创建整个路径。因此,LOG_DIR内容将在位置C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/中可见

提取时,我如何将里面的内容C:/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/

如果您不想重新创建完整路径,请将 chdir 放入主目录,并使源目录相对:

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";
chdir $home_dir;
my $src_location = "LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";

由于列表使用$File::Find::name,因此可以获得每个文件的绝对路径。这是你给Archive::Tar的名字,所以这就是它使用的名字。您可以在压缩包中看到文件:

$ tar -tzf archive.tgz

有多种方法可以获取相对路径。您可以在所需的函数中执行此操作。删除不需要的路径部分。这通常不会是你用于find(src_location(的目录,因为你想保持这种结构级别:

my @inventory;
find(
sub {
return if /A..?z/;
push @inventory, abs2rel( $File::Find::name, $home_dir )
}, $src_location
);

或者在以下之后执行:

@inventory = map { abs2rel($_, $home_dir) } @inventory;

最新更新