You are on the right track, but missing a couple of critical steps, which leaves you throwing out data that you don't want to throw out.
I'll walk through the first version you proposed, because I like it better (I personally find that style easier to read than the other one you mentioned, and it's also closer to being right):
opendir(LOGS,".");
sort @val = map { -M $_ } grep(/.*\.log/,readdir(LOGS));
Problem one: sort returns a (sorted) list, which you're discarding. So *if* everything else were right (we'll get there), you would want
@val = sort map {-M $_} grep {...
To see the bigger problem, we break it down a bit more, working from right to left down that line:
@tmp1 = readdir LOGS;
# @tmp now contains the files listed in "."
@tmp2 = grep {/.*\.log/} @tmp1;
#@ tmp2 now contains files that contain ".log"
@tmp3 = map {-M $_} @tmp2;
#@tmp3 now contains what?
@val = sort @tmp3;
If you re-read map, you'll discover that the list it generates is simply the result of the block {-M $_} applied to each value in @tmp2: since -M returns the age of the file, you now have a list of the ages of the log files in the directory, but *not* their names. Sort that list, and you have a sorted list of ages, but with no names associated with them. This is not what you wanted. :-)
What you *do* want is to associate age information with each of the items in @tmp1, sort on that, and get back the sorted version of @tmp1, which can be done thus:
use strict; #you are using strict, aren't you? ;)
my @val = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, -M $_] }
grep { /\.log$/ }
readdir LOGS;
(assuming I didn't drop any critical concepts in there). You may note that I implemented chromatic's suggestion (well, almost) and tagged a $ into the regex to match the end of the file name (so "foo.logger" doesn't match).
This is what's known as a Schwartzian Transform, a term you may or may not have encountered here before. It is very useful. It is also slightly strange to the naked eye--if it makes instant sense to you, congratulations! And if not, take some time to work it out (there are a couple good explanations attached to that link) , because it's a cool technique.
If God had meant us to fly, he would *never* have give us the railroads.
--Michael Flanders |