in reply to Add value from one array element into another of same ID
You need nested loops. The outer loop selects the data that you want to keep. The inner loop updates the CODE if a matching ID is found.
use strict; use warnings; use Data::Dumper; my $test_data = [ {'ID' => '1212', 'Name' => 'JOE' , 'Number' => 'XY1', 'CODE' => +'6',}, {'ID' => '1212', 'Name' => '' , 'Number' => 'XY1', 'CODE' => ' +10',}, {'ID' => '4456', 'Name' => 'MARIA', 'Number' => 'TYX', 'CODE' => +'6',}, {'ID' => '4456', 'Name' => '' , 'Number' => 'TYX', 'CODE' => ' +10',}, {'ID' => '8765', 'Name' => 'JEAN' , 'Number' => 'HPO', 'CODE' => +'6',}, ]; my @result; foreach my $data ( @{ $test_data } ) { next if !$data->{Name}; my $id = $data->{ID}; push @result, $data; foreach my $temp ( @{ $test_data } ) { if (!$temp->{Name} and ($temp->{ID} eq $id)) { $result[-1]->{CODE} = $temp->{CODE}; last; } } } print Dumper(\@result);
OUTPUT
$VAR1 = [ { 'ID' => '1212', 'CODE' => '10', 'Number' => 'XY 'Name' => 'JOE' }, { 'ID' => '4456', 'Name' => 'MARI 'Number' => 'TY 'CODE' => '10' }, { 'CODE' => '6', 'Number' => 'HP 'Name' => 'JEAN 'ID' => '8765' } ];
Bill
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Add value from one array element into another of same ID
by Anonymous Monk on May 27, 2021 at 19:44 UTC | |
by BillKSmith (Monsignor) on May 28, 2021 at 03:24 UTC |
In Section
Seekers of Perl Wisdom