我想获得每个组的条目数,但它似乎给了我错误的答案。每个组中都有可能重复的元素。结果我没有意义。我做错了什么?
my %hash;
while(<>)
{
chomp($_);
if(/(\d+)\t(\d+)/)
{
my $group = $1;
my $element = $2;
$hash{$group}{$element}=1;
}
}
foreach my $curr(keys %hash)
{
my $numElementsInCurr = keys %{$hash{$curr}};
print "$curr\t$numElementsInCurr\n";
}
答案 0 :(得分:0)
如果组中的元素可以重复,并且您需要计算包含这些重复项,则需要执行以下操作:
my %hash;
while(<>)
{
chomp($_);
if(/(\d+)\t(\d+)/)
{
my $group = $1;
my $element = $2;
++$hash{$group}{$element};
}
}
use List::Util 'sum';
foreach my $curr(keys %hash)
{
my $numElementsInCurr = sum values %{$hash{$curr}};
print "$curr\t$numElementsInCurr\n";
}