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
.
@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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With