in reply to ID exists in Hash -I need to copy the value even if it exists more than one
G'day MSOL,
Welcome to the monastery.
You appear to have messed up your HTML table markup (i.e. "<td <td <td <td <td <td"); however, from your initial description, I'll assume the data (as seen) is OK: please advise if this is a wrong assumption.
Sample input would have been useful: I've created dummy data (in the code below) based on your posted code. Again, please advise if my guess at this is wrong.
I also don't know how the output should be ordered. What you've shown appears grouped by key but otherwise haphazard.
To retain the order of keys as first seen in the input, this technique should suffice:
#!/usr/bin/env perl -l use strict; use warnings; my (%data, @order); while (<DATA>) { chomp; my ($key, $value) = split /\s*,\s*/; push @order, $key unless exists $data{$key}; push @{$data{$key}}, $value; } for my $key (@order) { print "|$key|$_|" for @{$data{$key}}; } __DATA__ 60,811 50, 813 34 , 820 32,821 34 ,820 32 , 821
Output:
|60|811| |50|813| |34|820| |34|820| |32|821| |32|821|
If you don't care about order (but still want to group the keys), you can just do this:
#!/usr/bin/env perl -l use strict; use warnings; my %data; while (<DATA>) { chomp; my ($key, $value) = split /\s*,\s*/; push @{$data{$key}}, $value; } for my $key (keys %data) { print "|$key|$_|" for @{$data{$key}}; } __DATA__ 60,811 50, 813 34 , 820 32,821 34 ,820 32 , 821
Hash keys aren't ordered so your output may well differ from mine; you may even get a different order each time you run the code. Here's the output from a sample run:
|34|820| |34|820| |60|811| |32|821| |32|821| |50|813|
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: ID exists in Hash -I need to copy the value even if it exists more than one
by MSOL (Initiate) on Mar 02, 2014 at 21:51 UTC |