Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map (and sort) values from a hash of hashes?

I have a hash of hashes, like so:

%hash = ( a  => { b => 1, c =>2, d => 3},
          a1 => { b => 11, c =>12, d => 13},
          a2 => { b => 21, c =>22, d => 23} )

I want to extract the "b" element and put it into an array. Right now, I am looping through the hash to do this, but I think I can improve efficiency slightly by using map instead. I'm pretty sure that if this was an array of hashes, I'd use something like this:

@hasharray = ( { b => 1, c =>2, d => 3},
               { b => 11, c =>12, d => 13},
               { b => 21, c =>22, d => 23} )
@array = map { ($_->{b} => $_) } @hasharray

Forgive me if I'm wrong, I'm still learning how map works. But what I'd like to know is how would I go about mapping the hash of hashes? Is this even possible using map? I have yet to find any examples of doing this.

Even better, the next step in this code is to sort the array once it's populated. I'm pretty sure this is possible, but I'm not smart enough on using map to figure it out myself. How would I go about doing this all in one shot?

Thanks. Seth

like image 868
sgsax Avatar asked Aug 27 '10 14:08

sgsax


1 Answers

This extracts and sorts all "b"s:

my @array = sort { $a <=> $b } map $_->{b}, values %hash;
like image 50
Eugene Yarmash Avatar answered Nov 01 '22 22:11

Eugene Yarmash