Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Insert into element into arrays ref

by aartist (Pilgrim)
on Aug 23, 2019 at 10:43 UTC ( [id://11104889]=note: print w/replies, xml ) Need Help??


in reply to Insert into element into arrays ref

We need to change the object pointed by each hashref of data1. It accommodates for multiple key/values in data2.
for my $hash1 (@{$data1}){ for my $hash2 (@{$data2}){ for my $key (keys %$hash2){ $hash1->{$key}=$hash2->{$key}; } } } print Dumper $data1;

Replies are listed 'Best First'.
Re^2: Insert into element into arrays ref
by AnomalousMonk (Archbishop) on Aug 23, 2019 at 14:25 UTC
    It accommodates for multiple key/values in data2.

    It accommodates multiple hashes in  $data2 with each hash having multiple key/values! This exceeds the implied requirement of the OP, but I find that requirements tend to expand spontaneously in these situations anyway.

    I was a bit daunted by the time-complexity of the triple nesting of your solution. I tried to come up with some alternatives. I think these all work, but neither your solution nor any of mine have been thoroughly tested by me. Unfortunately, I think the big-Os of all these solutions, yours and mine, are going to turn out to be exactly the same!

    foreach my $hashref (@$data1) { %$hashref = (%$hashref, %$_) for @$data2; } for my $hash1 (@$data1) { @{ $hash1 }{ keys %$_ } = values %$_ for @$data2; } foreach my $hash1 (@$data1) { for my $hash2 (@$data2) { map { $hash1->{$_} = $hash2->{$_} } keys %$hash2; } } for my $hash1 (@$data1) { for my $hash2 (@$data2) { while (my ($k2, $v2) = each %$hash2) { $hash1->{$k2} = $v2; } } }


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11104889]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-25 13:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found