Gossamer Forum
Home : General : Perl Programming :

Need help sorting by date.

Quote Reply
Need help sorting by date.
Can someone help me change this sort function, so I can pass in a date mm/dd/yyyy and have it sort by date in descending order?

Code:
sub sort_db{
foreach $curr (@results){
($key,@rest) = split(/\|/, $curr);
$max = @fields;

$code='$record{$key} = { key => "$key", ';

for($x=0;$x<$max;$x++){
$code .= "\$fields[$x] => \"\$rest[$x]\",\n";
} # End of for

$code .= '};';

eval $code;
} # End of foreach

$sort_on = "$fields[$sort]";

@results=();
foreach $rp (sort { chr($a->{$sort_on} + 97) cmp chr($b->{$sort_on} + 97) } values %record){
$new_rec = $rp->{key};
for($x=0;$x<$max;$x++){
$new_rec .= "\|$rp->{$fields[$x]}";
} # End of for
push @results, $new_rec;
} # End of foreach
} # End of sub sort_db


It's currently setup to sort alphabetically. What should I change to make it sort by date?
Quote Reply
Re: [Ryan] Need help sorting by date. In reply to
You are going to have real trouble trying to sort by a date in string format. Even writing a bit of code to manipulate it and sort it is going to be tricky.

It would be far better to store the date in epoch format.
Quote Reply
Re: [Paul] Need help sorting by date. In reply to
I'm not sure I understand what you mean... I think what I need is a date to unix function like what Links has. I was able to make Links sort by date using that function because it converts the dd-mmm-yyyy format to unix time. It seems like I could change this:

Code:
foreach $rp (sort { chr($a->{$sort_on} + 97) cmp chr($b->{$sort_on} + 97) } values %record){


to

Code:


foreach $rp (sort { &date_to_unix($a->{$sort_on}) <=> &date_to_unix($b->{$sort_on}) } values %record){


As long as I had a "date_to_unix" function that converts mm/dd/yyyy to unix time, it seems like that would work. The date to unix function in Links converts dd-mmm-yyyy. Can anyone help with this?

Last edited by:

Ryan: Feb 18, 2003, 10:02 AM
Quote Reply
Re: [Ryan] Need help sorting by date. In reply to
Yeah thats possible but storing the date in unix format in the first place would be better.

If that's not realistic then you will need to use a date module (like GT::Date) to convert the date string into a timestamp and then you will be able to sort.