http://qs321.pair.com?node_id=469354


in reply to No. files in folder

Since it's my code I guess I ought comment on it:
opendir my $d, $dir;
This should really have an or die for sanity and a more descriptive variable name than $d such as $dir_handle.
my @f = sort { -M $b <=> -M $a } readdir $d;
This sorts all the files in the directory by modification time in reverse chronological order, again, a more descriptive variable like @file_list would be better suited. It should also only grab files so a grep should be added i.e
my @file_list = sort { -M $b <=> -M $a } grep -f, readdir $dir_handle;
And finally:
unlink @f[-0,1] if @f > 20;
This removes the two oldest files if there are more than 20 elements in @f. This code is somewhat broken as the pathnames are not fully qualified, which could be done like so:
use File::Spec 'catfile'; unlink map catfile($dir, $_), @f[0,1] if @file_list > 20;
Also the negated zero in the original code was just a blip from knocking out a quick bit of code in the CB. So, in summary, this more thought out code would be better:
use File::Spec 'catfile'; opendir my $dir_handle, $dir or die "Couldn't open '$dir': $!"; my @file_list = sort { -M $b <=> -M $a } grep -f, readdir $dir_handle; unlink map catfile($dir, $_), @f[0,1] if @file_list > 20;
HTH

_________
broquaint