Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Add value from one array element into another of same ID

by Anonymous Monk
on May 27, 2021 at 19:44 UTC ( [id://11133163]=note: print w/replies, xml ) Need Help??


in reply to Re: Add value from one array element into another of same ID
in thread Add value from one array element into another of same ID

I think your code is doing something in reverse, noticed that I need to keep the values in the node where CODE => 10. But if I change the value in "Number" and run the code, it gets overwritten from the value in the node with "6":
use strict; use warnings; use Data::Dumper; my $test_data = [ {'ID' => '1212', 'Name' => 'JOE' , 'Number' => 'XY1', 'CODE' => +'6',}, {'ID' => '1212', 'Name' => '' , 'Number' => 'WW3', '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);

When it should be like this after running the code:
{'ID' => '1212', 'Name' => 'JOE' , 'Number' => 'WW3', 'CODE' => ' +10',},

Replies are listed 'Best First'.
Re^3: Add value from one array element into another of same ID
by BillKSmith (Monsignor) on May 28, 2021 at 03:24 UTC
    You can fix this problem by adding one line.
    ... $result[-1]->{CODE} = $temp->{CODE}; $result[-1]->{Number} = $temp->{Number}; ...

    I thought that I understood your requirements, but now I am not sure. I now think that you want one output record for each ID. For each ID, the input should contain one named record and possible one unnamed one. Output for any other input would be undefined. We probably cannot make any assumptions about record order. In the single record case, we output that record. In the two record case, we output the unnamed record with the value of its name field replaced with the name from the other record.

    Bill

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-19 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found