Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Sort an array which contains date formatted elements

by injunjoel (Priest)
on Jul 17, 2007 at 18:29 UTC ( #627095=note: print w/ replies, xml ) Need Help??


in reply to Sort an array which contains date formatted elements

Late to the game I see, but for the sake of TIMTOWTDI here is my suggestion.
Use a Schwartzian Transform.

use Time::Local; my %months; @months{('jan','feb','mar','apr','may','jun','jul','aug','sep','oct',' +nov','dec')} = 0..11; my @lines = map{ $_->[1] } sort{ $a->[0] <=> $b->[0] } map{ chomp; my $val = $_; $val =~ s#webadmin_([^\.]+)\.log#my @t=split(/_/,$1);timelocal +(0,0,0,$t[1],$months{$t[0]},($t[2]-1900))#e; [$val,$_]; }<DATA>; print "$_\n" for(@lines); __DATA__ webadmin_jul_10_2007.log webadmin_jul_11_2007.log webadmin_jul_12_2007.log webadmin_jul_13_2007.log webadmin_jul_14_2007.log webadmin_jul_7_2007.log webadmin_jul_8_2007.log webadmin_jul_9_2007.log
The Output
webadmin_jul_7_2007.log webadmin_jul_8_2007.log webadmin_jul_9_2007.log webadmin_jul_10_2007.log webadmin_jul_11_2007.log webadmin_jul_12_2007.log webadmin_jul_13_2007.log webadmin_jul_14_2007.log


-InjunJoel
"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo


Comment on Re: Sort an array which contains date formatted elements
Select or Download Code
Re^2: Sort an array which contains date formatted elements
by johngg (Abbot) on Jul 17, 2007 at 22:13 UTC
    I agree with your suggestion to use a ST but my preference would be to use a regex to pull out the month, day and year elements and do a three-way sort, greping only those filenames that match.

    use strict; use warnings; my %months; @months{qw{ jan feb mar apr may jun jul aug sep oct nov dec}} = 0 .. 11; my $rxWanted; { local $" = q{|}; $rxWanted = qr {(?x) \A webadmin _(@{ [ keys %months ] }) _(\d\d?) _(\d{4}) \.log \z }; } print map { qq{$_->[0]\n} } sort { $a->[3] <=> $b->[3] || $months{$a->[1]} <=> $months{$b->[1]} || $a->[2] <=> $b->[2] } grep { defined $_->[1] } map { chomp; [ $_, m{$rxWanted} ] } <DATA>; __END__ . .. webadmin_jul_10_2007.log webadmin_jul_11_2007.log webadmin_jul_12_2007.log webadmin_jul_13_2007.log webadmin_jul_14_2007.log webadmin_jul_7_2007.log webadmin_jul_8_2007.log webadmin_jul_9_2007.log user.log

    The output is as yours.

    Cheers,

    JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://627095]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2014-07-10 23:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls