opendir my $d, $dir or die "Can't readdir $dir: $!"; my @files = grep -f $_, # collect only the files in folder map "$dir/$_", readdir $d; # make full pathnames to the files closedir $d; # close directory handle # sort using a "Schwartzian Transform" my @sorted = map $_->[ 0 ], # untag sort { $b->[ 1 ] <=> $a->[ 1 ] } # sort according to age map [ $_, -M $_ ], # tag files with their "ages" @files; unlink @sorted[ 0, 1 ] if @sorted > 20;