kiruthika kiruthika - 1 month ago 7
Perl Question

How can I sort dates in 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
.

Answer
@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;
Comments