Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Is this the most elegant way to code directory lookup?

by jasonk (Parson)
on Sep 29, 2006 at 16:29 UTC ( #575569=note: print w/replies, xml ) Need Help??


in reply to Is this the most elegant way to code directory lookup?

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://575569]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2021-06-13 09:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (54 votes). Check out past polls.

    Notices?