in reply to Messing about in Arrays of Hashes
A first go at it, that will work even if the ids are not sorted (assuming we start with $var):
my %hash; $hash{$_->{id}} += $_->{value} for @$var; $var = [ map { +{id => $_, value => $hash{$_} } } sort keys %hash ];
Second go, based on your initial assumption, possibly more efficient but uglier for sure:
my $lastind = -1; for my $i (0 .. @$var - 1) { if ($var->[$i]->{id} eq $var->[$lastind]->{id}) { $var->[$lastind]->{value} += $var->[$i]->{value}; splice @$var, $i, 1; } else { $lastind = $i; } }
|
|---|