[TriLUG] Perl problem

Aaron S. Joyner aaron at joyner.ws
Tue Jun 8 17:12:35 EDT 2004


Just a few things off the cuff.  First off, specify the whole path.  
Your stat($f) should read stat("$dir/$f").

Also, other things to be aware of: are you sure you have permission to 
read the other directory you're testing with?  You need at least read 
and execute permissions to the directory the files reside in, and at 
least execute permissions on every parent directory all the way back to /.

As just an off-the-cuff suggestion, if this isn't part a bigger PERL 
script, or a learning exercise, it's an awful lot easier and faster to 
do this with a single find command.  Something like this:
find -mtime +1d -exec rm \{\} \;

On the other hand, if you're reasons for doing it in PERL are justified 
there's a lot simpler way to accomplish the same task with the -M test 
something like this:
if (-M "$dir/$file" > $threshold) { print "File is older than $threshold 
days\n"; }
Note that $threshold can be fractional.  Also note that you can test 
access time with -A and there are other variations if you need them.

The latter two solutions are a good bit more elegant, in my opinon, but 
all things are good in the interest of learning.

Aaron S. Joyner


Stephen Hoffman wrote:

>Having a problem with a perl script.  It is mainly to flush files out of a
>directory once a nightly backup has occured.  So here's what it's SUPPOSED
>to do.
>   Look in a directory for files older then a certain number of days and
>simply delete them.  At first glance it works quite well, but upon
>further inspection I can't specify any other directory then the one
>that the perl script resides in.  So where I have $dir="." that can be
>$dir="/path/to/current/directory" and it still works, but if I specify
>a directory elsewhere it claims that the files in that directory were
>last modified on the Epoch date and are 12K+ days old.
>
>Am I missing something?
>
>Any help GREATLY appreciated.
>
>Steve
>
>
>#!/usr/bin/perl -w
>use strict;
>
>my $threshold = 1;
>print "Deleting files older than $threshold days\n";
>
>my $dir = ".";
>
>opendir(D,$dir) or die $!;
>my $time = time();
>
>while (my $f = readdir(D)) {
>    next if $f =~ /^\./;
>    my ($atime, $mtime, $ctime) = (stat($f))[8..10];
>    my $age_hours = ($time - $mtime) / 3600;
>    my $age_days  = int($age_hours / 24);
>    next unless $age_days > $threshold;
>    print "---> Deleting $f ($age_days days)...";
>####################    unlink $f;
>    print " done\n";
>}
>
>closedir(D);
>  
>




More information about the TriLUG mailing list