Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort dates in Perl?

Tags:

sorting

perl

How can I sort the dates in Perl?

my @dates =  ( "02/11/2009" , "20/12/2001" , "21/11/2010" ); 

I have above dates in my array . How can I sort those dates?

My date format is dd/mm/YYYY.

like image 791
kiruthika Avatar asked Mar 22 '10 10:03

kiruthika


1 Answers

@dates = sort { join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]) } @dates;

or using separate sorting subroutine:

sub mysort {
    join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]);
}
@dates = sort mysort @dates;

Update: A more efficient approach is the Schwartzian Transform:

@dates = 
    map $_->[0],
    sort { $a->[1] cmp $b->[1] }
    map  [ $_, join('', (split '/', $_)[2,1,0]) ], @dates;
like image 128
Eugene Yarmash Avatar answered Oct 01 '22 04:10

Eugene Yarmash