in reply to Get average value of array of numbers

use List::Util qw(sum); sub mean { return sum(@_)/@_; }

sum returns the summation of all the elements in the array. Dividing by @_ (which in scalar context gives the number of elements) returns the average.

Replies are listed 'Best First'.
Re^2: Get average value of array of numbers
by AnomalousMonk (Archbishop) on Oct 15, 2009 at 19:27 UTC
    Dividing by @_ (which in scalar context gives the number of elements) returns the average.
    What happens if the array is empty (0 elements)?

    Maybe:

    >perl -wMstrict -le "use List::AllUtils qw(sum); sub mean { return @_ ? sum(@_) / @_ : 0 } my @Array = (3, 5, 7, 12,24); print mean(@Array); print mean(); " 10.2 0
    Update: Per oha: What is the proper result of averaging zero elements? 0? undef? A divide-by-zero (or some other) exception? Something else? Any of these results can easily be supported. I wanted to make the point that this boundary condition should at least be considered.
Re^2: Get average value of array of numbers
by swampyankee (Parson) on Oct 15, 2009 at 19:49 UTC

    …although to be a bit more rigorous you should divide by the number of defined elements, and check to ensure that there is at least one (defined) element in the array.


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

Re^2: Get average value of array of numbers
by Anonymous Monk on Oct 15, 2009 at 14:10 UTC
    Great, thanks!