Zielfelder, Robert wrote:
I have a sorting problem I need to solve but I'm not sure how to go about it. I have an application that dumps a file with a format like this: 19JAN2006.1503 03JAN2006.1647 19DEC2004.0530 24MAR2003.1115 As you may have guessed, these are dates and times - timestamps for log files from an application. I want to be able to sort this list from earliest to latest date. I'm able to parse these into specific categories (Year, Month, Day, Time) and can sort on any one category, but I don't know how to sort by multiple categories. Anyone have any ideas?
I suggest you provide a function that will transform the filenames into something that's sortable using the standard sort operator. The program below uses a subroutine 'reformat' which splits the filename into day, month, year, and time strings, uses a hash to translate the month name into a number, and glues them all together again in a different order. Once this is written, the sort block can compare the result of applying the function to its two parameters and produce a list sorted in date order as required. Forget about anything fancier than necessary until you find your program is running too slowly. Hashes and Schwartzian transforms are devices for improving speed at the expense of clarity. HTH, Rob use strict; use warnings; my @file = qw/ 19JAN2006.1503 03JAN2006.1647 19DEC2004.0530 24MAR2003.1115 /; my %month; @month{qw/JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC/} = '01' .. '12'; foreach ( sort { reformat($a) cmp reformat($b) } @file) { print $_, "\n"; } sub reformat { my $date = shift; my ($d, $m, $y, $hhmm) = $date =~ /(\d+)([A-Z]+)(\d+)\.(\d+)/; "$y$month{$m}$d$hhmm"; } **OUTPUT** 24MAR2003.1115 19DEC2004.0530 03JAN2006.1647 19JAN2006.1503 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>