Sami_R has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I am new to PERL, stuck on looping through the hash of array and convert hash with key and value please.

Have ...

$VAR1 = [ { 'name' => 'Tim', 'total' => 4, 'months' => 1, 'days' => 3 }, { 'total' => 22, 'name' => 'Adam', 'days' => 22 }, { 'name' => 'Keas', 'total' => 114, 'months' => 5, 'days' => 107, 'test' => 2 } ];

How to loop through this and convert into like below ?

$VAR1 = { 'Tim' => { 'total' => 4, 'months' => 1, 'days' => 3 }, 'Adam' => { 'total' => 22, 'days' => 22 }, 'Keas' => { 'total' => 114, 'months' => 5, 'days' => 107, 'test' => 2 } };

Thanks in advanced.

Replies are listed 'Best First'.
Re: How to loop through hash of array and convert into hash with key and value.
by stevieb (Canon) on Dec 28, 2019 at 02:35 UTC

    What you actually have there is an array of hashes.

    Since the delete function returns the item that was deleted, we can use it directly in the assignmnent:

    use warnings; use strict; use Data::Dumper; my $aref = [ { 'name' => 'Tim', 'total' => 4, 'months' => 1, 'days' => 3 }, { 'total' => 22, 'name' => 'Adam', 'days' => 22 }, { 'name' => 'Keas', 'total' => 114, 'months' => 5, 'days' => 107, 'test' => 2 } ]; my $href; $href->{delete $_->{name}} = $_ for @$aref; print Dumper $href;

    Output:

    $VAR1 = { 'Adam' => { 'days' => 22, 'total' => 22 }, 'Keas' => { 'total' => 114, 'test' => 2, 'days' => 107, 'months' => 5 }, 'Tim' => { 'total' => 4, 'days' => 3, 'months' => 1 } };
      Elegant solutions, thanks.
Re: How to loop through hash of array and convert into hash with key and value.
by NetWallah (Canon) on Dec 28, 2019 at 02:33 UTC
    Verified working code:
    $VAR1 = { map { $_->{name} => $_ } @$VAR1 };
    Don't be shy about asking specific, detailed questions on how/why that works, after researching the "map" function.

                    "From there to here, from here to there, funny things are everywhere." -- Dr. Seuss

      Mapping worked after modifying like...
      my $VAR3 = { map { delete $_->{name} => $_ } @$VAR1 };
      Thanks.

      Unfortunately, this doesn't address removing the name from the inner hash references.

Re: How to loop through hash of array and convert into hash with key and value.
by NetWallah (Canon) on Dec 28, 2019 at 02:40 UTC
    A more "traditional" approach:
    my $VAR2; for my $h (@$VAR1){ $VAR2->{ $h->{name} } = $h; } print Dumper \$VAR2;

                    "From there to here, from here to there, funny things are everywhere." -- Dr. Seuss

      Great solutions, thank you so much.