CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Sorting Hashes

 



andy7t
User

Sep 12, 2003, 12:42 PM

Post #1 of 5 (675 views)
Sorting Hashes Can't Post

Hello,

I'm making a Football game and the script at which i am stuck is the league generating script.

OK, so here's my question.

$team = "TEAMNAME";

$leaguepos= "LEAGUEPOSITION";

$hash{$team} = $leaguepos;

OK, so how do i sort the $hash so that the $teams are sorted in order of there $leaguepos.



E.G

$hash{'Arsenal'} = "3";

$hash{'Man U'} = "1";

$hash{'Chelsea'} = "4";

$hash{'Newcastle'} = "2";



Would produce:

Man U, Newcastle, Arsenal, Chelsea.

Thanks.


KevinR
Veteran


Sep 12, 2003, 4:26 PM

Post #2 of 5 (673 views)
Re: [andy7t] Sorting Hashes [In reply to] Can't Post

why not just make two hashes, one with the ranking as the key and one with the team name as the key, then sort/print the hash you want to display.

$team = "TEAMNAME";

$leaguepos= "LEAGUEPOSITION";

$hash1{$team} = $leaguepos;


$hash2{ $leaguepos} = "TEAMNAME";

then to print the hash:



foreach
$key (sort keys %hash2){
print
"$hash2{$key}<br>";
}


or:

foreach
$key (sort keys %hash2) {
printf(
"%s. $hash2{$key}<br>", $key);
}

-------------------------------------------------


(This post was edited by KevinR on Sep 12, 2003, 4:31 PM)


andy7t
User

Sep 13, 2003, 4:36 AM

Post #3 of 5 (667 views)
Re: [KevinR] Sorting Hashes [In reply to] Can't Post

Good thinking!

Why didn't i think of that...


KevinR
Veteran


Sep 13, 2003, 11:29 AM

Post #4 of 5 (663 views)
Re: [andy7t] Sorting Hashes [In reply to] Can't Post

hehehe.... Smile
-------------------------------------------------


davorg
Thaumaturge / Moderator

Sep 17, 2003, 1:40 PM

Post #5 of 5 (644 views)
Re: [andy7t] Sorting Hashes [In reply to] Can't Post


Code
foreach (sort { $hash{$a} <=> $hash{$b} } keys %hash) { 
print "$hash{$_} - $_\n";
}


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives