Reversing a multi-valued hash in perl

I have a hash that looks like this:

{ bmw      => { id => 1, color => brown } }
{ mercedes => { id => 2, color => black } }

I want to change this hash in perl to just get the id => name_of_car mapping. Do I need to use the inverse function somehow?

Note. I can always iterate over the original hash and assign keys and values ​​accordingly in the new hash, I want to know if there was a smoothing method.

+5
source share
2 answers

No need to use a smooth way:

my %h = (
    bmw      => { id => 1, color => "brown" } ,
    mercedes => { id => 2, color => "black" } 
);
my %j = map { ($h{$_}{id} => $_) } keys %h;

for (keys %j) {
    print "$_ $j{$_}\n";
}

Conclusion:

$ ./silly.pl 
1 bmw
2 mercedes
+6
source

What you posted is incorrect, but I think I understand your meaning. One easy way to do this would be with a hash fragment and a map.

my %hash = (
    bmw      => { id => 1, color => 'brown' },
    mercedes => { id => 2, color => 'black' },
);
my %new_hash;
@new_hash{ map { $_->{id} } values %hash } = keys %hash;
+2
source

All Articles