cvirus96 cvirus96 - 4 months ago 6x
Perl Question

Deleting files over 90 days in Perl

I am currently trying to delete all files over 90 days old in a directory. The only solution I can think of is more work than I think is necessary. Is there a quick and easy way to do this? If you were working with this code:

my $date=POSIX::strftime('%b%Y', localtime);
my $logDir = "/test/dir/"
my $dateDir = "$logDir/$date
#this directory contains files with the form of


Here's a way using File::Find::Rule, as it keeps the full path information. The important piece for the comparison is -M $file > 90. -M returns the number of days since the file was last modified.

use warnings;
use strict;

use File::Find::Rule;

my $dir = '.';
my $days = 90;

my @files = File::Find::Rule->file()

for my $file (@files){
    if (-M $file > 90){
        print "deleting $file\n";
        unlink $file or warn $!;

Note the maxdepth() method says "don't traverse into sub directories". Set that to 0 if you want to look in sub dirs.

Also, if you want to specify a specific name, you can add a name() method, which will take regexes and only operate on those files. eg: name('*.2016*')