in reply to unlink files

There is more than one way to do this, and the "correct" way depends on the minute details of your setup. Here's the code i use in my framework (this isn't exactly from the most modern module i have, but it works):

# Use the object oriented version of stat use File::stat; ... sub _dircleaner($self, $dir, $maxagedays) { my $reph = $self->{server}->{modules}->{$self->{reporting}}; $reph->debuglog("Scanning $dir for cleaning"); my @todelete; my $deletes = 0; my $ok = 1; my $dfh; if(!opendir($dfh, $dir)) { $reph->dblog("DIR_CLEANER", "Can't open '$dir'"); $dbh->commit; $reph->debuglog("Can't open $dir"); $ok = 0; goto finishcleaning; } my $fcount = 0; my $maxage = $maxagedays * 3600 * 24; # Convert days to seconds my $now = time(); while((my $fname = readdir($dfh))) { next if($fname eq "." || $fname eq ".."); # FIXME FOR SUBDIRS! CLEAN UP SUBDIRS, THEN REMOVE ALL EMPTY D +IRS next if(!-f "$dir/$fname"); my $fileage = stat("$dir/$fname")->mtime; my $age = $now - $fileage; next if($age <= $maxage); push @todelete, "$dir/$fname"; $fcount++; } closedir($dfh); if($fcount) { $reph->debuglog("Cleaning $fcount file(s) in $dir"); foreach my $fname (@todelete) { if(unlink $fname) { $deletes++; $reph->debuglog(" ...deleted $fname"); } else { $ok = 0; $reph->debuglog("Failed to delete $fname"); } } $reph->debuglog("Deleted $deletes file(s)."); } finishcleaning: return $ok; }

Basically, i read the whole directory in and remember the files i want to delete, then delete them one-by-one. The relevant steps for filtering the files is:

# Convert age (in days) to seconds my $maxage = $maxagedays * 3600 * 24; # Convert days to seconds # get the "last modified" timestamp of the file in SECONDS (unix times +tamp) my $fileage = stat("$dir/$fname")->mtime; # Current time in seconds (unix timestamp) my $now = time; # Age in seconds my $age = $now - $fileage; # Ignore file if it is too new next if($age <= $maxage); # Add files to the "@todelete" list with full filename push @todelete, "$dir/$fname";