Perl 如何通过唯一键对数组值求和?

Perl 如何通过唯一键对数组值求和?,perl,Perl,比如说 array ( product1_quantity => 5, product1_quantity => 1, product2_quantity => 3, product2_quantity => 7, product3_quantity => 2, ) 结果: product1_quantity - 6, product2_quantity - 10, product3_quantity - 2 塔克斯 对不起,伙计们 愚蠢的例子,相反,这真

比如说

array (
product1_quantity => 5,
product1_quantity => 1,
product2_quantity => 3,
product2_quantity => 7,
product3_quantity => 2,
)
结果:

product1_quantity - 6, 
product2_quantity - 10, 
product3_quantity - 2
塔克斯


对不起,伙计们

愚蠢的例子,相反,这真的

数组([0]=>数组([product1]=>7) [1] =>阵列([product1]=>2) [2] =>阵列([product2]=>3) )

?

新的数组将包含Perl中的和:

my %hash = ();
$hash{'product1_quantity'} += 5;
$hash{'product1_quantity'} += 1;
$hash{'product2_quantity'} += 3;
$hash{'product2_quantity'} += 7;
$hash{'product3_quantity'} += 2;

say join ",\n", map { "$_ - $hash{$_}" } keys %hash;
输出为:

product2_quantity - 10,
product3_quantity - 2,
product1_quantity - 6
顺序是不同的,但您可以通过添加排序强制其“有序”:

say join ",\n", map { "$_ - $hash{$_}" } sort {$a cmp $b} keys %hash;

您可能需要类似于:

  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;
这表明:

$VAR1 = 'product2_quantity';
$VAR2 = 10;
$VAR3 = 'product3_quantity';
$VAR4 = 2;
$VAR5 = 'product1_quantity';
$VAR6 = 6;

不过要注意——如果你的数量值中有任何未定义项,这将很难打破。您需要有一个偶数长度的产品/数字数量对数组。

一次从两个项目中提取项目,并添加到散列中

my @array = (
        product1_quantity => 5,
        product1_quantity => 1,
        product2_quantity => 3,
        product2_quantity => 7,
        product3_quantity => 2,
);
my %sums;
while (@array and my ($k,$v) = (shift(@array),shift(@array)) ) {
        $sums{$k} += $v;
}

嗯,语言?通常,每个键只能有一个值。所以你提供的数组甚至是无效的。我不知道有哪种语言可以对不同的值使用相同的键。@felix,neo-这些可能只是一些元组让我看看我现在是否理解了。您想要一个数组,其中每个元素都是一个数组,每个元素都是一个键/值对?或者内部数组的每个元素都是一组键/值对吗?另外:您想用它实现什么?Perl允许数组和散列之间轻松地互换,因为散列整体上的计算结果被报告为数组,其中每两个项组成一个键/值对。因此,您可以这样做:my@array=(this=>'that',foo=>'bar',this=>'other');我的%hash=@array;#两个键,“这个”被覆盖了。哎哟,没注意到这和另一个答案基本相同,他比我领先了两个小时。很抱歉当我写这篇文章时,在最初的文章中没有提到Perl——请参阅文章的修订历史。。“谢谢”为-1
my @array = (
        product1_quantity => 5,
        product1_quantity => 1,
        product2_quantity => 3,
        product2_quantity => 7,
        product3_quantity => 2,
);
my %sums;
while (@array and my ($k,$v) = (shift(@array),shift(@array)) ) {
        $sums{$k} += $v;
}