Jeff 'japhy' Pinyan wrote:
On Jul 6, Ryan Frantz said:
I'm working on a script that will generate a listing of files on a
regular basis so that I can create hyperlinks to each respective file.
As you see from the sorted output below, though it is in ASCIIbetical
order, it is not in chronological order:
/2005Jul01-2005Jul02/foo/bar.html
/2005Jul05-2005Jul06/foo/bar.html
/2005Jun09-2005Jun10/foo/bar.html
/2005Jun10-2005Jun11/foo/bar.html
/2005Jun13-2005Jun14/foo/bar.html
/2005Jun14-2005Jun15/foo/bar.html
Is there any decent documentation available that I could study so that I
can sort this better?
I thought about grabbing the ctime of each file and sorting on that but
I'm not sure if that would add unnecessary complexity to the script.
The primary problem is that the dates in the filenames are formatted as
"YYYYmmmDD" rather than "YYYYMMDD". Before sorting the filenames, you
could convert the month NAMES to numerical representations (Jan => 01,
Dec => 12), and then after you've sorted them (ASCIIbetically will work
here) you can change those numerical representations back to the month
names.
from Programming Perl's 'Efficiency' chapter:
"Sorting on a manufactured key array may be faster than using a fancy
sort subroutine. A given array value may participate in several sort
comparisons, so if the sort subroutine has to do much recalculation,
it's better to factor out that calculation to a separate pass before the
actual sort." :-)
such as, for example, building the hash keys on the fly as you slurp in
the dir names/paths into that key's value . . . (hint, hint, did the
lightbulb go off yet?)
%month2num = ( Jan => 01, Feb => 02, ...Jun => 06, ... Dec => 12);#fixme
foreach ( qw[ /2005Jun13-2005Jun14/foo/bar.html ] ) {
my $fullpath = $_;
my ($y1, $m1, $d1, $y2, $m2, $d2) =
m(
^/ # starting slash
(\d{4}) # year
(\w{3}) # monthname
(\d{2}) # day
- # a dash
(\d{4}) # etc, etc,
(\w{3})
(\d{2})
/
)x
or warn "$pathname didn't match!" && next;
my ($MD1, $MD2) = $month2num{ $m1 }, $month2num{ $m2 };
$squid{"$y1$MD2$d1-$y2$MD2$d2"} = $fullpath;
}
print "$squid{$_}\n" foreach sort keys %squid;
Of course, there are certain constraints involved with regards to how
much memory you'll use if your list is long... :)
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>