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

Hi Monks!
I have this sub routine running to delete files older then 7 days, but I think that this line " if ($now-(stat $file)[9]  > $age) { # file older than 7 days" is not getting the numbers right, even if I just create a new file it still gets seeing, can someone see what I can't!
sub del_old{ my $age = 60*60*24*7; # convert 7 days into seconds my $now = time(); # get current time # Delete files older than 7 days. opendir (DIR, "old") or die "Couldn't open directory, $!"; while (my $file = readdir DIR) { next if $file=~/^\./; if ($now-(stat $file)[9] > $age) { # file older than 7 days print "This $file wil be deleted\n"; } } closedir DIR; }

Thanks for looking!

Replies are listed 'Best First'.
Re: Delete old files
by Corion (Patriarch) on Mar 17, 2014 at 19:03 UTC

    The second paragraph of readdir deals with your problem. In short, you need to prepend "old" to $file. Also see File::Find and/or glob.

      Looked at this and it still gives me any files in the directory:
      ... my @file_list; while (my $file = readdir DIR) { next if $file=~/^\./; push @file_list, $file; } closedir DIR; for my $files (@file_list) { my @stats = stat($files); if ($now-$stats[9] > $age) { # files older than 7 days print "$files\n"; } } ...

        How did you change the construction of the entries in @file_list after reading the second paragraph of readdir?

        Also, why not use the following instead of the loop?

        my @file_list= glob("$old/*");
Re: Delete old files
by Anonymous Monk on Mar 17, 2014 at 19:11 UTC