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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.