map for hashes in Perl

Tim picture Tim · Apr 24, 2011 · Viewed 24.7k times · Source

Is there a hash equivalent for map?

my %new_hash = hash_map { new_key($a) => new_val($b) } %hash;

I know that I could loop through the keys.

Answer

Dallaylaen picture Dallaylaen · Apr 24, 2011

List::Pairwise claims to implement exactly that syntax -- see mapp, grepp. I haven't used it though.

Also, you can do it as

%new_hash = map { new_key($_) => new_value($hash{$_}) } keys %hash; 

which I admit looks clumsier if %hash is really a $deeply->{buried}->{hash}. I prefer using $temp = ...; map {...} keys %$temp in such cases.