通常,如果你想在 Perl 中对一些数据进行分组,你会使用 hashes。这些散列的键对应于分组标准,值用作累加器(它可以是一个简单的数字,如本例所示,也可以是等待稍后处理的数字数组)。
这是一种方法:
use warnings;
use strict;
# this hash will hold all the cumulatives
my %sums;
# here we scan the source, line by line
# each line is split to key and value
while (<DATA>) {
chomp;
my ($label, $value) = split;
# this line uses the auto-vivification Perl feature:
# if there's no corresponding item in %sums hash, it'll be created (with 0 value)
$sums{$label} += $value;
}
# here we process the resulting hash:
for my $key (sort keys %sums) {
print $key, ' ', $sums{$key}, "\n";
}
__DATA__
aggr3 350.01000213623
aggr3 1228.79999923706
aggr5 250
aggr3 1536
aggr3 690.01000213623
aggr3 1587.20000076294
aggr9 550.01000213623
aggr3 1228
aggr5 905
aggr5 100
键盘演示。