You need something similar to:
use Data::Dumper; my @input = ( product1_quantity => 5, product1_quantity => 1, product2_quantity => 3, product2_quantity => 7, product3_quantity => 2, ); my %output; while (my $product = shift(@input) and my $quantity = shift(@input)) { $output{$product} += $quantity; } print Dumper %output;
This spits out:
$VAR1 = 'product2_quantity'; $VAR2 = 10; $VAR3 = 'product3_quantity'; $VAR4 = 2; $VAR5 = 'product1_quantity'; $VAR6 = 6;
Be warned, though, if you have any undefs in your quantitative values, it will break a lot. You should have an even array of product pairs / numerical values.
Oesor source share