Hi guys, quite rusty on my Perl as I've been stuck doing other stuff for quite some time. Am currently trying to help a colleague sort out an issue he has with a small Perl script he's inherited.
Basically, the script reads in some data in the form of:
USERID1|2215|Jones,Tom| USERID1|1000|Jones, Tom| USERID3|1495|Dole, Bob| USERID2|2500|Francis, Pope| USERID2|1500|Francis, Pope|
The goal is to process each of these records, keep a running total of the values in the second field, then output the ID, the sum of the second field for that ID, and the name.
I managed to fix a couple of minor things that were wrong in it (no trailing pipe on the end of the record causing additional blank lines in the output, small things like that), but am not sure on the best way to handle this with the additional field. The (broken) code he currently has is:
#!/usr/bin/perl use strict; use warnings; my ($key,$value,$reason); my %sum=(); while(<>) { unless(/.*\|(\d+)/){print STDERR "dropped line: \"$_\""; next;} ($key,$value,$reason) = split(/\|/); $sum{$key}+=$value; } foreach $key (keys %sum){print "$key|$sum{$key}|$reason\n";}
Running the above gives the following result:
USERID3|1495|Francis, Pope USERID1|3215|Francis, Pope USERID2|4000|Francis, Pope
The obvious issue here is $reason - it's not being stored anywhere during the loop, so just repeating the $reason from the last record in the data... but I'm not sure of the best way to do this? It's easy enough when just dealing with the first two fields, as you can use a simple hash, as is being done already.
I'm just not sure of the best way to add the extra info into this? Is a hash of hashes required to get the additional element in? I've not played with complex hashes before, so suggestions/examples would be much appreciated.
In reply to Best way to store/sum multiple-field records? by bobdabuilda
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |