Try this on for size... Probably still not the way I would approach the problem, but at least it's a bit more elegant...
my $srcdir ='/var/local/some_dir';
my $mtime = 1;
my $destdir = '/backup/some_dir';
# Yours doesn't tell you which directory didn't exist...
die "$srcdir does not exist" unless -d $srcdir;
die "$destdir does not exist" unless -d $destdir;
print "Beginning backup...\n";
# Error checking on chdir is important too, the directory
# might exist, but not be readable by you
chdir $srcdir or die "Can't change to $srcdir: $!";
# Once your program gets bigger than a couple of lines,
# you really want to know which directories or files
# couldn't be opened
opendir ( INDIR, $srcdir ) or die "Can't open $srcdir: $!";
# if this is a big directory, slurping all the files into
# memory can be quite a waste of memory...
while ( my $file = readdir( INDIR ) ) {
next if -d $file; # -d will be true for . and .. too
if ( -M $file > $mtime ) {
print "$file : Older than one day.\n";
next;
}
# tar is for combining multiple things into one,
# gzip is for compressing, since you are only doing
# one file at a time, the tar is just wasted effort
system( "gzip -c $file > $destdir/$file.gz" );
if ( $? != 0 ) { die "Gzip failed" }
print "$file archived in $destdir\n";
}
This is probably how I would actually approach the problem... Although this approach may not meet some requirements that couldn't really be inferred from your code...
use Path::Class qw( dir );
my $srcdir = dir( '/var/local/some_dir' );
my $destdir = dir( '/backup/some_dir' );
$destdir->mkpath unless -d $destdir;
die "$srcdir does not exist" unless -d $srcdir;
die "$destdir does not exist" unless -d $destdir;
print "Beginning backup...\n";
while ( my $file = $srcdir->next ) {
next if $file->is_dir;
my $target = $destdir->file( $file->basename.".gz" );
if ( $file->stat->mtime <= $target->stat->mtime ) {
print "backup is more recent than original\n";
next;
}
system( "gzip -c $file > $target" );
if ( $? != 0 ) { die "Gzip failed" }
print "$file archived in $destdir\n";
}
We're not surrounded, we're in a target-rich environment! |
---|