Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Add new rows and data to array.

by kcott (Archbishop)
on Mar 20, 2020 at 01:43 UTC ( [id://11114501]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-19 06:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found