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


in reply to No. files in folder

opendir my $dir, $dir;

This line opens a handle (which is saved as $d) to the directory found at path $dir (so $dir could be defined as '/home/myuser/thedir').

my @f = sort { -M $b <=> -M $a } readdir $d;

This is the sort of line that shows what perl can do. There's a couple of things going on here, so we can break it down to see what's happening. This statement basically works backwards. First the readdir($d) generates a list of files and directories being read from the $d directory handle. If the directory at $dir contains foo1.dat, foo2.dat, subDir1, subDir2, foo3.dat, then you will get those 5 items listed through readdir(). This list of files is then passed to the sort routine, which is the part enclosed in curly braces. The -M $b <=> -M $a sorts the list of files by the last modified time of the file -- the end result from this sort will be the list of files read from the readdir(), which we are placing in the @f array. Because of the way we've sorted the list, the oldest files will be at the front of the array, with the newest files at the end.

unlink @f[0,1] if @f > 20;

As I said earlier, the @f array now contains the list of files, with the oldest files listed at the front of the array (so elements 0 and 1 would be your oldest 2 files). So the conditional statement on the size of @f checks to see if we have more than 20 files, and if so, executes unlink() on the first 2 entries to have them deleted.

I'd probably rewrite the code as follows to also ensure we are only dealing with files, just in case you have any directories in that main directory we do not want to include. Warning: my perl is quite rusty, there is a good chance the following code will not run, and if it does, it may not work as expected.

my $dir = '/path/to/the/files'; opendir(my $d, $dir) or die("opendir() failed: $!"); my @sort_files = sort { -M($b) <=> -M($a) } grep { -f($_) } readdir($d); unlink(map { "$dir/$_" } @f[0, 1]) if (@sort_files > 20);