Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by texasperl (Sexton)
on Sep 29, 2006 at 15:12 UTC ( [id://575546]=note: print w/replies, xml ) Need Help??


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

With your helpful suggestions I have modified my code as follows. Better? I hope so. =]
#!/usr/bin/perl use warnings; use strict; use File::Copy; # change source backup dir, modification time, and destination backup +dir here my $srcdir = '/var/local/somedir'; my $mtime = '1'; my $destdir = '/backup/somedir'; die "Error:$!" unless (-d $srcdir && -d $destdir ); print "Beginning backup...\n"; chdir $srcdir; opendir(INDIR,$srcdir) || die "Can't open directory: $!"; while ($_ = readdir(INDIR)) { next if (-d || $_ eq "." || $_ eq ".."); if (-M > $mtime) { print "$_ : Older than one day.\n"; } else { system("tar -cz $_ -f $_.tar.gz"); move(<*.gz>, $destdir) && print "$_ archived in $destd +ir\n"; } } closedir(INDIR); print "Backup complete.\n";

Replies are listed 'Best First'.
Re^2: Is this the most elegant way to code directory lookup?
by davorg (Chancellor) on Sep 29, 2006 at 15:20 UTC
    die "Error:$!" unless (-d $srcdir && -d $destdir );

    As I mentioned before, $! won't have anything useful in it at this point, so there's no reason to include it in the error message.

    Why not make the error messages a little clearer.

    die "$srcdir is not a valid directory\n" unless -d $srcdir; die "$destdir is not a valid directory\n" unless -d $destdir;

    Update: Looks like I'm wrong.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      Update: Looks like I'm wrong.

      I disagree: just because someone tried it once and got a useful error message doesn't change the fact that $! is not documented to be defined at this point.

      $! may well get set differently (or not at all) in different circumstances, when testing different files, or on a different O/S, or depending on phase of the moon for all we know.

      Your suggested clearer error messages are definitively more correct; the only change I might make (at the risk of getting too clever) is to avoid the duplication with something like:

      die "$_ is not a valid directory\n" for grep !-d, $srcdir, $destdir;

      Hugo

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-19 21:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found