perl:如何将哈希中的多个值计入新哈希?

时间:2017-11-05 17:50:54

标签: perl

我目前的哈希:

%hash = (
  "foo",
   [
     "apple",
     "orange",
     "apple",
     "apple"
  ],
  "bob",
  [
    "apple",
    "orange",
  ],
);

如何获得此输出?

%hash2 = (
  apple  => 4,
  orange => 2,
);

1 个答案:

答案 0 :(得分:3)

my %counts;
for (values(%hash)) {  # Iterate over the values of the hash, the references to the arrays.
   for (@$_) {         # Iterate over the values of the referenced array.
      ++$counts{$_};
   }
}

my %counts;
++$counts{$_} for map @$_, values %hash;