mbeason has asked for the wisdom of the Perl Monks concerning the following question:

Exhalted monks, I'm trying to write a script which looks in a directory and looks for files older than X days. I've tried a few different methods but can't seem to return the files I'm expecting. Here is a portion of my humble script:
use File::stat; use Time::Local; chomp(my $host = `hostname`); my($timestamp) = strftime "%Y%m%d", localtime; my($humantime) = strftime "%c", localtime; my($standard_days) = 7; my($mksysb_cutoff) = (time() - ($standard_days*86400)); # now - standa +rd_days_seconds &cleanup; sub cleanup { opendir(MOUNT, "/mnt") or die "Cannot open directory: $!"; @mksysb_list = readdir MOUNT; closedir MOUNT; foreach my $mksysb (@mksysb_list) { next if($mksysb eq ".") or ($mksysb eq "..") or ($mksysb eq "l +ost+found"); if($mksysb =~ /\d+\.$host\.mksysb/) { my $curr_time=(stat("$mksysb"))[9]; if ($curr_time < $mksysb_cutoff) { print "I would have deleted |$mksysb|!\n"; } } }
I've also tried doing a if(-M $mksysb); as well after the "next" line but with no luck. If I put a print statment before the $curr_time declaration, I get a listing of the files so I know at least that part is working. HELP!

Replies are listed 'Best First'.
Re: Compare mtime?
by xdg (Monsignor) on Mar 14, 2006 at 19:41 UTC

    Just a thought -- could this be a result of using File::stat? When you use it, it overrides the built-in stat to return a File::stat object that you access like this:

    my $fs = stat($file); my $mtime = $fs->mtime();

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      That was it! I didn't realize that there was a built-in stat function. Once I removed the reference to File::stat, it worked like a charm. Thanks!
Re: Compare mtime?
by rafl (Friar) on Mar 14, 2006 at 19:43 UTC

    My approach would look like that:

    use File::Find::Rule; my @files = File::Find::Rule->file ->in('/mnt') ->name( qr(\d+\.$host\.mksysb) ) ->maxdepth(1) ->mtime(">= $mksysb_cutoff");

    Actually I already have a script running that pretty much works like that and it works well.

    Cheers, Flo

Re: Compare mtime?
by Zaxo (Archbishop) on Mar 14, 2006 at 20:02 UTC

    The -M operator returns the age in days wrt the script start time, so what you want can be as simple as this:

    my $dir = '/path/to'; my $max_age = '5 days'; for (<$dir/*>) { -M > $max_age and print "I would have deleted $_.\n"; }
    I could have set $max_age to numerical 5, but I like having the unit for self-documentation. As long as the numerals are first in the string, Perl does what I want.

    After Compline,
    Zaxo

Re: Compare mtime?
by smokemachine (Hermit) on Mar 14, 2006 at 20:09 UTC
    could be this?
    while(<$dir/*>){push @old, $_ if (time-(stat $_)[9]) >= ($day * 86400) + && $_ ne "lost+found"}