How to match (and sort) values ​​from hash hashes?

I have a hash of a hash, for example:

  % 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 element "b" and put it in an array. Right now, I am going through a hash to do this, but I think I can improve performance by using a map instead. I am sure that if it were an array of hashes, I would 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 am mistaken, I am still studying how the card works. But what I would like to know is how am I going to display the hash of the hashes? Is this possible with a card? I have not found examples of this yet.

Even better, the next step in this code is to sort the array after it is populated. I'm sure this is possible, but I'm not smart enough to use the card to figure it out myself. How can I do this in just one shot?

Thanks. Set

+6
sorting perl map hash-of-hashes
source share
3 answers

This extracts and sorts all the "b" s:

my @array = sort { $a <=> $b } map $_->{b}, values %hash; 
+11
source share

This populates @array sorted list of @array references, each of which contains the value b and hashref from which it came.

 my @array = sort {$$a[0] <=> $$b[0]} map { [$$_{b} => $_] } values %hash; my @sorted_hashes = map {$$_[1]} @array; 
+3
source share

Take the second solution and replace values %hash with @hasharray :

 @array = map { ($_->{b} => $_) } values %hash; 

(And don't forget that ; completes the statement.)

+1
source share

All Articles