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:
Sort hash twice

 



yiati
New User

Sep 27, 2011, 8:34 PM

Post #1 of 2 (462 views)
Sort hash twice Can't Post

I am currently trying to take a hash which has words stored in the keys, and the number of occurences stored in the values. I want to output the key/value pairs so that the key/value pairs with the highest value are listed first, and of the key/value pairs that have the same value, I want to output those in alphabetical order with respect to their key's.

Example:

Input: c!c b!b a!a v!v v!v t!t t!t

Output: t!t:2, v!v:2, a!a:1, b!b:1, c!c:1

At the moment I am trying to use a foreach loop, but it's not working. The output is working numerically how I want, but not working lexically.


Code
foreach my $word (sort { $wordHash{$b} <=> $wordHash{$a} || $wordHash{$a} <=> $wordHash{$b} } keys %wordHash) 
{
print "$word:$wordHash{$word}\n";
}



yiati
New User

Sep 27, 2011, 10:19 PM

Post #2 of 2 (451 views)
Re: [yiati] Sort hash twice [In reply to] Can't Post

JK Solved it!


Code
foreach my $word (sort { $wordHash{$b} <=> $wordHash{$a} || $a cmp $b } keys %wordHash) 
{
print "$word \t ($wordHash{$word})\n";
}


 
 


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

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