Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

problems sorting hashes of hashes

by Anonymous Monk
on Jun 30, 2000 at 22:06 UTC ( [id://20644]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am having problems sorting a two dimentional hash. I have checked the prerequisite help sites (the stuff here at perlmonks.org) and perldsc, but they don't seem to work for my situation.

Normally I'd chug away at it untill I got it to work, but I needed it to work yesterday ... : )

So without further ado, here is the offending code, printing unsorted:

foreach $auth (keys %hash) { print FILE "$hash{$auth}{fname} $hash{$auth}{lname}: $hash{$auth}{c +ount}\n"; }
my data structure is set up as follows:
$hash{author} has three fields, fname (first name), lname (last name), and count (number of occruences in a file)

I would like to sort the hash by the count field.

Any help would be greatly appreciated.

-- steve

Replies are listed 'Best First'.
Re: problems sorting hashes of hashes
by btrott (Parson) on Jun 30, 2000 at 22:08 UTC
    Here you go:
    for my $auth (sort { $hash{$b}{count} <=> $hash{$a}{count} } keys +%hash) { print FILE "$hash{$auth}{fname} $hash{$auth}{lname}: $hash{$au +th}{count}\n"; }
    This will sort by count in reverse numerical order, from biggest count to smallest. If you want it the other way round, swap the $a and $b.
      thank you!

      looking at your code, it makes perfect sense

      you wouldn't believe the stuff i was tryin to do before .. : )

      -- steve

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://20644]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-19 06:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found