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: Beginner:
sorting a hash by its keys

 



sayal
Novice

Apr 6, 2011, 5:30 AM

Post #1 of 3 (379 views)
sorting a hash by its keys Can't Post

Hi,

i tried to understand how to sort a hash by its keys. I do not understand why i have to get the keys of the hash first. And i do not understand how to use the function sort(). Are there several ways to sort? By the way the hash i want to sort has numeric values as keys.

Regards

sayal


BillKSmith
Veteran

Apr 6, 2011, 6:08 AM

Post #2 of 3 (377 views)
Re: [sayal] sorting a hash by its keys [In reply to] Can't Post

This question is answered at some length in FAQ that come with perl.

Refer: perldoc -q sort hash



Strictly speaking, you cannot sort a hash. You can only sort the keys or the values. The hash cannot preserve that order.
Good Luck,
Bill


Karazam
User

Apr 6, 2011, 6:48 AM

Post #3 of 3 (372 views)
Re: [sayal] sorting a hash by its keys [In reply to] Can't Post

A hash in Perl does not keep its elements in any particular order. Normally this is not a
problem, since the values are retrieved by keys, not position. Sometimes you may still want
a sorted output, and there are ways to do this, depending on what your specific needs are.
To name just a few:

1. Consider if you should maybe use an array instead.

2. If you just want to retrieve the values in a sorted fashion you can use the sort function.
For numerical sort:


Code
for my $key ( sort { $a <=> $b } keys %hash ) { 
print $hash{$key};
}


3. If you want to preserve the order in which the elements were added to the hash, then
you can use the Tie::IxHash module.

 
 


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

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