in reply to Re: HOW to calculate the column data
in thread HOW to calculate the column data

No need to use an array, you just need to store two values, the total and the count:

my %vals_by_type; while ( <DATA> ) { my ( $type, $val ) = split; $vals_by_type{ $type }{ total } += $val; $vals_by_type{ $type }{ count }++; } for my $type ( sort keys %vals_by_type ) { my $avg = $vals_by_type{ $type }{ total } / $vals_by_type{ $type } +{ count }; printf "%s %.2f\n", $type, $avg; }

Replies are listed 'Best First'.
Re^3: HOW to calculate the column data
by ikegami (Patriarch) on Dec 03, 2009 at 21:26 UTC

    The difference is that I divided each value *before* summing them for extra precision. But I'll grant you that it's surely not needed here.

    Storing them in an array is also useful if you want to perform more than one operation, especially if the operation requires all the elements (like finding the median).

    By the way,
    $vals_by_type{ $type }{ count }++;
    is less efficient than
    ++$vals_by_type{ $type }{ count };