Search code examples
perlperl-data-structures

Folding Array of hashes to HoH


I have $maps as AoH which I wish to make a $new_map to be a HoH based on a member of the enclosing hashes.

I currently have:

map { $new_map->{$_->{TYPE}} = $_; delete $_->{TYPE} } @$maps;

This does the job..

I wonder if there's a better/simpler/cleaner way to get the intent. Perhaps, by getting the return value from map?

$new_map = map { ... } @$maps; 

Thanks


Solution

  • Your original solution is a misuse of map as it doesn't use the list that the operator returns. for is the correct tool here, and I think it reads much better that way too, especially if you use the fact that delete returns the value of the element it has removed

    $new_map->{ delete $_->{TYPE} } = $_ for @$maps;
    

    Or you could translate the array using map properly, as here

    my %new_map = map { delete $_->{TYPE} => $_ } @$maps;
    

    The choice is your own