Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by jdporter (Canon)
on Sep 29, 2006 at 16:03 UTC ( #575566=note: print w/replies, xml ) Need Help??


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

I would eliminate the use of chdir. Yes, the program as given works, but only because both of the directories are specified as absolute. I think you'd gain flexibility by allowing relative paths (for example, "." as the srcdir).

Here's how I might rewrite it:

#!/usr/bin/perl use Getopt::Long; use strict; use warnings; $|=1; my $srcdir; my $destdir; my $mtime = 1; GetOptions( 'srcdir=s' => \$srcdir, 'destdir=s' => \$destdir, 'mtime|days=i' => \$mtime, ); defined $srcdir && defined $destdir or die <<EOF; Usage: $0 --srcdir SRCDIR --destdir DESTDIR [-days N] EOF opendir SRCDIR, $srcdir or die "opendir $srcdir - $!"; my @too_old; my @files; # only select non-hidden regular files: for ( grep { -f "$srcdir/$_" } readdir SRCDIR ) { if ( -M "$srcdir/$_" > $mtime ) { push @too_old, $_; } else { push @files, $_; } } closedir SRCDIR; @too_old and print "(Ignoring ".scalar(@too_old)." too-old files.)\n"; @files or die "No backup candidates in $srcdir."; unless ( -d $destdir ) { warn "Destination directory $destdir does not exist; attemptin +g to create.\n"; mkdir $destdir or die "mkdir $destdir - $!"; } print "Backing up ".scalar(@files)." files from $srcdir.\n"; for my $f ( @files ) { print "Archiving $f \n"; system qq( cd "$srcdir" ; tar -cz "$f" -f "$f.tar.gz" ); system qq( mv "$srcdir/$f.tar.gz" "$destdir" ); }

This doesn't entirely avoid chdir, but it puts it at the lowest, most constrained context possible. In fact, if you have gnu tar (which it appears you do), you can exploit the -C option to make tar itself do the directory change within itself.

We're building the house of the future together.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2021-06-24 16:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (130 votes). Check out past polls.

    Notices?