my %values; while () { my ($col, $val) = split; # store the sum and number of occurrences in a hashref $values{$col}[0] += $val; $values{$col}[1]++; } for my $col (sort keys %values) { print "$col ", $values{$col}[0] / $values{$col}[1], "\n"; }