Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a hash 1

Status
Not open for further replies.

BenRussell

Programmer
Mar 12, 2001
243
US
I want to find out how to sort a hash in numerical order (largest to smallest) still keeping its name and value intact.

For instance if the hash was :
%Hash = ("FirstName", "1", "ThirdName", "3", "FourthName", "4", "FifthName", "5");

how would I sort the 1,3,4,5 still keeping their names (FirstName, SecondName, etc.) intact? - Ben Russell
- President of Intracor Technologies (
 
You can't really sort a hash per-se, but you can sort it as you iterate through it. You can get a sorted list of the keys or values. HOWEVER, you can't get the key of a hash based on it's value, so in this case you might do better to invert the keys and the values of the hash and then iterate through a sorted list of the keys (numbers) so you can access the values (names).

That being said, here is a way of iterating through the keys of a hash in order of their values, which is what you want:
Code:
foreach my $key (sort 
   {$Hash{$a} <=> $Hash{$b}} (keys %Hash)) {
   # process the hash here
} # end foreach
This sorts the hash by NUMERIC values. To sort by STRING values change the <=> in the block to cmp. Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
That depends on what you want to do with the sorted hash. For example, to just print the key/value pairs in order by value:
Code:
   $val = $Hash{$key};
   print &quot;key/value: $key / $val\n&quot;;
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top