Home: Perl Programming Help: Intermediate:
Sorting Hashes



andy7t
User

Sep 12, 2003, 12:42 PM


Views: 1622
Sorting Hashes

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


Views: 1620
Re: [andy7t] Sorting Hashes

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


Views: 1614
Re: [KevinR] Sorting Hashes

Good thinking!

Why didn't i think of that...


KevinR
Veteran


Sep 13, 2003, 11:29 AM


Views: 1610
Re: [andy7t] Sorting Hashes

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


davorg
Thaumaturge / Moderator

Sep 17, 2003, 1:40 PM


Views: 1591
Re: [andy7t] Sorting Hashes


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