# Sorting on sub-hash values

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

If I have a hash of hashes like this:

my %hash= ( 'bob' => { 'age' => 35,  'weight' => 160 },
'john' => { 'age' => 22,  'weight' => 138 },
'sue' => { 'age' => 31,  'weight' => 143 } );

and I want to sort people by their age, how would I go about it?

Thanks

Ian

## Re: Sorting on sub-hash values

What have you tried?  Given a name, how would you access the age
of that person?

Anno

## Re: Sorting on sub-hash values

nothing as yet.. I've been surfing on the matter for a while now but haven't
found anyone asking/describing the same question/desire

foreach my \$k (keys %hash) {
print \$hash;
}

Ian

## Re: Sorting on sub-hash values

On Thu, 23 Jun 2005 10:30:21 +0100, IanW wrote:

Well, presumably, you already know how to sort the keys of %hash
alphabetically?

# Note to gurus: I know the coderef is not needed, but
# it clarifies the explanation

my @sorted_keys = sort { \$a cmp \$b } keys %hash;

Here, \$a and \$b will be varying keys of %hash when the sort coderef is
called.

I would expect that you also know how to get the age of a person out of
your data structure, for any particular person:

my \$johns_age = \$hash->;

Putting these 2 ideas together leads pretty quickly to:

my @sorted_keys = sort -><=>\$hash->} keys %hash

Can you see what's going on here? You're feeding a list of the keys of
%hash to the sort function. In the coderef for the sort, you're using the
keys that are passed in (in \$a and \$b) to dive into %hash and produce the
age values so they are compared for the sort.

HTH
Rich

## Re: Sorting on sub-hash values

Yes

Yes

<sound of penny dropping>

It most certainly does.. THANKYOU! :-)

Ian

IanW wrote:

perldoc -q sort

Mark