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


in reply to Insert into element into arrays ref

No need to futz around with map. Just push the contents of @{$data2} onto @{$data1}.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: Insert into element into arrays ref
by Anonymous Monk on Aug 22, 2019 at 18:43 UTC
    Using push:

    push @$data1, @$data2;

    Result:
    [ { 'DATE' => '2009-05-05', 'NAME' => 'PAUL DY', 'NUMBER' => '00001' }, { 'NAME' => 'ANTHONY RD', 'NUMBER' => '00003', 'DATE' => '2012-01-07' }, { 'NUMBER' => '00023', 'NAME' => 'RUTH RD', 'DATE' => '2018-01-07' }, { 'CODE' => 'X11' } ]

    Looking for this:
    [ { 'NAME' => 'PAUL DY', 'DATE' => '2009-05-05', 'NUMBER' => '00001', 'CODE' => 'X11', }, { 'NAME' => 'ANTHONY RD', 'DATE' => '2012-01-07', 'NUMBER' => '00003', 'CODE' => 'X11', }, { 'NAME' => 'RUTH RD', 'DATE' => '2018-01-07', 'NUMBER' => '00023', 'CODE' => 'X11', }, ]

    Thanks!

      One way (update: see the Perl Data Structures Cookbook):

      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', } ]; foreach my $hashref (@$data1) { %$hashref = (%$hashref, %{ $data2->[0] }); } print Dumper $data1; __END__ $VAR1 = [ { 'NAME' => 'PAUL DY', 'DATE' => '2009-05-05', 'CODE' => 'X11', 'NUMBER' => '00001' }, { 'NAME' => 'ANTHONY RD', 'DATE' => '2012-01-07', 'CODE' => 'X11', 'NUMBER' => '00003' }, { 'NAME' => 'RUTH RD', 'DATE' => '2018-01-07', 'CODE' => 'X11', 'NUMBER' => '00023' } ];

      Update 1: Note that using this method, if there is a key in the hash referent of the single element of the  $data2 array referent that is the same as one in a hash referent of any  $data1 array referent, the value of the former will silently overwrite the value of the latter. (Update: For instance, see what happens if  $data2 happens to be
          my $data2 = [ { 'CODE' => 'X11',  'NAME' => 'JONES', } ];
      instead. (Update: This exact problem is discussed more clearly in the FAQ referenced by BillKSmith here.))

      Update 2: Here's a testing framework for playing around with other approaches. See Test::More, Test::NoWarnings.


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

      You are merging the hash in $data2 with each of the hashes in $data1. Read the FAQ.
      perldoc -q "How do I merge two hashes?"
      Bill