Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I archive a directory in Perl like tar does in UNIX?

Tags:

tar

perl

I want to archive a directory (I don't know whether I can call "I want to tar a directory"). I want to preserve the access permissions at the other end when I un-tar it. I should I tackle this problem in perl.

Thanks for the response but why I'm asking for doing it Perl is I want it independent of the platforms. I want to transfer one big file to multiple machines. Those machines can be of any platform. I should be able to untar this tar file properly right? So I want to write my own tar and untar programs. Why I'm using Perl is to make it platform independent. So I can not use tar command by opening the shell in script and stuff like that. The Archive::Tar module only deals with tarred file but it has no option to archive files.

like image 509
Ram Avatar asked Feb 05 '09 11:02

Ram


2 Answers

Here is a simple example:

#!/usr/bin/perl -w

use strict;
use warnings 'all';
use Archive::Tar;

# Create a new tar object:
my $tar = Archive::Tar->new();

# Add some files:
$tar->add_files( </path/to/files/*.html> );
# */ fix syntax highlighing in stackoverflow.com

# Finished:
$tar->write( 'file.tar' );

# Now extract:
my $tar = Archive::Tar->new();
$tar->read( 'file.tar' );
$tar->extract();
like image 57
JDrago Avatar answered Dec 21 '22 23:12

JDrago


Two parameters; the name of the compressed tar file and the name of directory you want in the tar file. eg

tarcvf test.tar.gz mydir
#!/usr/bin/perl -w 

use strict;
use warnings 'all';
use Archive::Tar;
use File::Find;


my $archive=$ARGV[0];
my $dir=$ARGV[1];

if ($#ARGV != 1) {
    print "usage: tarcvf test.tar.gz directory\n";
    exit;
}

# Create inventory of files & directories
my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $dir);

# Create a new tar object
my $tar = Archive::Tar->new();

$tar->add_files( @inventory );

# Write compressed tar file
$tar->write( $archive, 9 );
like image 38
Colin Avatar answered Dec 22 '22 00:12

Colin