PDA

View Full Version : sort dates in perl


meha19
02-23-2005, 07:27 AM
Hi,

I need to sort dates of the following format "dd/mm/yy".

Eg:

@pubdate = ('07/12/04', '22/11/04', '28/09/04', '28/03/05' );

Kindly do let me know if anyone has some help.

Thanks & Regards,
Meha

mlseim
02-23-2005, 04:34 PM
http://www.codingforums.com/archive/index.php/t-39927

meha19
02-25-2005, 11:56 AM
Hi, Thanks forur reply. I tried the sample given & for this set of data im sending it throws an error "Month '12' out of range 0..11 at sortdate.pl line 26". what could be the reason ?

file : sortdate.pl

use Time::Local;

@dates = ('10/07/2004', '12/07/2004', '12/07/2004');


print "@dates\n";

@ordered = sort { &compare } @dates;

sub compare {
$a =~ /(\d{2})\/(\d{2})\/(\d{4})/;
$amonth = $1;
$aday = $2;
$ayear = $3;

$b =~ /(\d{2})\/(\d{2})\/(\d{4})/;
$bmonth = $1;
$bday = $2;
$byear = $3;

$c = timelocal(0,0,0,$aday,$amonth,$ayear-1900);
$d = timelocal(0,0,0,$bday,$bmonth,$byear-1900);

$c <=> $d;
}

print "@ordered\n";

Thanks & Regards,
Meha

mlseim
02-25-2005, 03:09 PM
The other example also failed, but I see a typo they made and
now it works. I actually tried it (no errors).

If your dates are like: 10/02/04 instead of 10/02/2004,
change the "d{4}" to "d{2}" on both lines in subroutine.
The "4" represents 4 characters (as in the year).

To summarize what the script is doing:
1) takes the array and looks at the first date.
2) converts the item "10/02/2004" to "20041002".
3) looks at the next item and does the same.
4) compares which one is greater and moves the elements around.
5) it does this "recursively" throughout the whole array until it's done.

==========================================================

#!/usr/bin/perl

print "Content-type: text/html\n\n";

@dates = ('10/02/2004', '02/01/2004', '12/02/2004', '01/06/2004', '01/02/2005', '01/12/2004');

print "Original List: @dates <br><br>\n";

@ordered = sort { &compare } @dates;

sub compare {
$a =~ /(\d{2})\/(\d{2})\/(\d{4})/;
$c = $3 . $1 . $2;

$b =~ /(\d{2})\/(\d{2})\/(\d{4})/;
$d = $3 . $1 . $2;

$c <=> $d;
}

print "Ordered List: @ordered\n";


##

nosaku
10-15-2009, 08:40 PM
Change the following lines:

$amonth = $1;
$bmonth = $1;

to:

$amonth = $1-1;
$bmonth = $1-1;

Regards,
Satish.