Here is a start:
You would pull from the hash, but easier for testing to just use __DATA__ and
using map , I have the following setup:
0 - the date
1 - month
2 - day
3 - year
So you compare first vs year, then if necessary to month followed by day.
Like I say, a start for you.
foreach my $key (sort { $a->[3] <=> $b->[3] || $a->[1] <=> $b->[1] || $a->[2] <=>
$b->[2]} map{ [ $_, /^(\d+).(\d+).(\d+)/ ] } <DATA>) {
printf "%-s", $key->[0];
}
__DATA__
12/01/01
02/01/02
11/15/01
12/14/00
^----Script ends here
Output:
12/14/00
11/15/01
12/01/01
02/01/02
Wags ;)
-----Original Message-----
From: Pellerin, Dale [mailto:[EMAIL PROTECTED]]
Sent: Wednesday, November 28, 2001 08:03
To: [EMAIL PROTECTED]
Subject: Sorting a Hash
I am very new to hashes (as well as Perl) and am having some difficulty with
a cgi script. This script allows individuals to post "announcements" via a
form. The form data is stored in a text file, sorted in descending order by
date, and printed to the html page. However, the script is currently
sorting by the month and not by the year, thus creating a problem when news
items are posted from 2002. (01/01/02 news items are being printed below
12/01/01 news items)
Here is a sample of the text file that the data is stored in:
http://is-blah.com/corprate/pages/news/cafeteria_closed.htm ~ 10/24/01 ~
Cafeteria closed
Here is a snippet of code from the cgi script that sorts the file:
# Hash to sort date
$from = "tmc.dat";
my %h;
open(FILE, "$from") || die "Can't open $from!\n";
while (<FILE>) {
chomp;
($announcement,$date,$description) = split(/~/,$_);
# if the date has already been seen, tack this entry on to the hash value
if( $h{$date} ){
$h{$date} .= "|$announcement~$description";
}
# date hasn't been seen, so create a new hash entry
else
{
$h{$date} = "$announcement~$description";
}
}
#sort the dates in desc. order
foreach $key (sort {$b cmp $a} keys %h)
{
#do for each item for that date
@items = split '\|', $h{$key};
foreach $item (@items)
{
#split back out the values and print the table
my($announcement,$description) = split /~/,$item;
print "<table width=800><tr>";
print "<td><img border=0 width=14 height=14 id='_x0000_i1027'
src='http://is-web/corprate/gifs/blueball.gif'>";
print "<ALIGN='left'><span style='font-size:13.5pt'><a
href=\"$announcement\"><font color=blue>$description</font></a>(<font
color=black> $key)</font></td>";
print "</tr></table><br>";
I would appreciate any assistance in figuring out how to sort by year, then
by month.
Thank you.
Dale
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]