To sort date in "DD MMM YYYY" format (e.g. "02 DEC 2010")
#/usr/bin/perl -w
use strict;
# Constants
my %MONTH_NUMBER = (
'JAN' => 1,
'FEB' => 2,
'MAR' => 3,
'APR' => 4,
'MAY' => 5,
'JUN' => 6,
'JUL' => 7,
'AUG' => 8,
'SEP' => 9,
'OCT' => 10,
'NOV' => 11,
'DEC' => 12,
);
my @myarray = (
'08-DEC-10',
'30-NOV-10',
'26-NOV-10',
'25-NOV-10',
'25-NOV-10',
'24-NOV-10',
'11-NOV-10',
'10-NOV-10',
'10-NOV-10',
'08-NOV-10',
'03-NOV-10',
'02-NOV-10',
'01-NOV-10',
);
my @sorted_array = sort sort_func @myarray;
print "@sorted_array";
####################
# Subroutine
####################
# Sort function
sub sort_func() {
# To sort in desc, just swap $a and $b
#return convert_datenumber($b)
# cmp convert_datenumber($a);
return convert_datenumber($a)
cmp convert_datenumber($b);
}
# Convert "DD MMM YYYY" into "YYYYMMDD"
sub convert_datenumber() {
my $in_date = $_[0];
my $out_date = 0;
if (length($in_date)) {
my $day = substr($in_date, 0, 2);
my $month = $MONTH_NUMBER{ substr($in_date, 3, 3) };
my $year = substr($in_date, 7);
$out_date = $year * 10000
+ $month * 100
+ $day;
}
return $out_date;
}
Output:
01-NOV-10 02-NOV-10 03-NOV-10 08-NOV-10 10-NOV-10 10-NOV-10 11-NOV-10 24-NOV-10 25-NOV-10 25-NOV-10 26-NOV-10 30-NOV-10 08-DEC-10