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! |
---|
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.