http://www.perlmonks.org?node_id=11104876


in reply to Insert into element into arrays ref

Another way - UPDATING the contents of $data1 without replacing them,
and arguably easier on the eyes:
while(my($k,$v)=each %{$data2->[0]}){ $_->{$k} = $v for @$data1; }
UPDATE: Changed "for" to "while" to accomodate multi-key hashref in $data2, per aartist (++).

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

Replies are listed 'Best First'.
Re^2: Insert into element into arrays ref
by AnomalousMonk (Archbishop) on Aug 23, 2019 at 05:04 UTC
    for (my($k,$v)=each %{$data2->[0]}){ $_->{$k} = $v for @$data1; }

    That works for a single key/value element in $data2->[0], but given that it can work for only a single element, why not use the ocularly even easier

    my ($k,$v) = %{$data2->[0]}; $_->{$k} = $v for @$data1;

    c:\@Work\Perl\monks>perl use strict; use warnings; use Data::Dumper; my $data1 = [ { 'NAME' => 'PAUL DY', 'DATE' => '2009-05-05', 'NUMBER' => '00001', }, { 'NAME' => 'ANTHONY RD', 'DATE' => '2012-01-07', 'NUMBER' => '00003', }, { 'NAME' => 'RUTH RD', 'DATE' => '2018-01-07', 'NUMBER' => '00023', }, ]; my $data2 = [ { 'CODE' => 'X11', 'X' => 'Y', } ]; for (my($k,$v)=each %{$data2->[0]}){ $_->{$k} = $v for @$data1; } print Dumper $data1; __END__ $VAR1 = [ { 'NAME' => 'PAUL DY', 'X' => 'Y', 'DATE' => '2009-05-05', 'NUMBER' => '00001' }, { 'NAME' => 'ANTHONY RD', 'X' => 'Y', 'DATE' => '2012-01-07', 'NUMBER' => '00003' }, { 'NAME' => 'RUTH RD', 'X' => 'Y', 'DATE' => '2018-01-07', 'NUMBER' => '00023' } ];


    Give a man a fish:  <%-{-{-{-<

      for (my($k,$v)=each %{$data2->[0]}){

      You may need to use while in place of for to get all the value in %{$data2->[0]}