F Massion <
fmas...@web.de> writes:
> I have built a hash with multiple values per key. The values are numeric and
> I would like to add all the values per key get a list of key with the sum of
> values. When it comes to add the values I get stuck. Anyone has a hint? Her
> my code:
You could write a simple function that returns the sum of its arguments (or
use sum() from List::Util), and pass each key's array to it. For example:
#!/usr/bin/env perl
use 5.010; use warnings; use strict;
my %hash;
foreach my $line (<DATA>) {
chomp $line;
my ($key1, $key2, $value) = split /\t/, $line;
push @{$hash{"$key1\t$key2"}}, $value;
}
foreach my $key (sort keys %hash) {
say "$key: ", sum(@{$hash{$key}});
}
sub sum {
my $n = shift @_;
return $n unless @_;
return $n + sum(@_);
}
__DATA__
RecordID001 adjustment washer 100
RecordID001 adjustment washer 1
RecordID001 adjustment washer 2
RecordID001 adjustment washer 2
RecordID002 scraper plate 0
RecordID003 scraper plate, lh side 6
RecordID004 scraper plate, rh side 50
RecordID004 scraper plate, rh side 51
--
Aaron --
aaron.baugher.biz