in reply to Add new rows and data to array.
In the following code, I've cut down the input data to the minimum required to demonstrate the technique that I've used.
#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my $data = [ { status => 'Main', City => 'NY', zCode => '0002', ID => '2222' } +, { status => 'Extra', City => 'BO', zCode => '0007', ID => '2222' } +, { status => 'Cabin', City => 'NE', zCode => '4562', ID => '2222' } +, { status => 'Main', City => 'AA', zCode => 'TTTT', ID => '8888' } +, { status => 'Test', City => 'BB', zCode => 'WWWW', ID => '8888' } +, { status => 'Cabin', City => 'CA', zCode => '2334', ID => '8888' } +, ]; my %new = (City => 'new_City', zCode => 'new_z_code'); my %extra; $extra{$_->{ID}} = $_ for grep +($_->{status} eq 'Extra'), @$data; for my $row (@$data) { next unless $row->{status} eq 'Main'; %$row = (%$row, map +($new{$_} => exists $extra{$row->{ID}} ? $extra{$row->{ID}}{$_} : '' ), keys %new ); } dd $data;
Output:
[ { City => "NY", ID => 2222, new_City => "BO", new_z_code => "0007", status => "Main", zCode => "0002", }, { City => "BO", ID => 2222, status => "Extra", zCode => "0007" }, { City => "NE", ID => 2222, status => "Cabin", zCode => 4562 }, { City => "AA", ID => 8888, new_City => "", new_z_code => "", status => "Main", zCode => "TTTT", }, { City => "BB", ID => 8888, status => "Test", zCode => "WWWW" }, { City => "CA", ID => 8888, status => "Cabin", zCode => 2334 }, ]
You should only need to add two key-value pairs to %new for a full solution.
Consider simply adding 'new_' to the existing keys for a more standard naming convention. This would make comparing keys easier; if not a requirement now, it could be at a later date. It would also allow you to simplify my code, as follows:
my @new = qw{City zCode ...}; ... map +("new_$_" => exists ... ), @new
— Ken
|
|---|