in reply to minimum, maximum and average of a list of numbers at the same time
As others have mentioned, you are unlikely to code anything in Perl that will beat List::Util for performance, even if you do avoid making 3 whole passes. That is the nature of a dynamic language.
For error handling, you need to add code to detect and deal with them. You have to decide whether to die or croak within the subroutine, or return some failure indication (like an empty list).
Here's one possibility that raises an exception (via die) within the sub and catches it in the calling code using the block form of eval:
#! perl -slw use strict; sub minMaxAve { die 'Empty list' unless @_; my( $min, $max, $sum ); for( @_ ) { die 'Non-numeric value(s)' unless /^[\de+.-]+$/; $min = $_ if !defined $min or $min > $_; $max = $_ if !defined $max or $max < $_; $sum += $_; } return $min, $max, $sum / @_; } for ( [], [ 1 .. 4 ], [ 5 , 1, 5, 6, 5 ], [ 1, 2, -0.1, 1e-5, 2e10 ], [ 'fox', 'dog' ] ) { my @results = eval{ minMaxAve @$_ } or warn "[ @$_ ] : $@\n\n" and + next; printf "[ %s ]\nmin: %g max: %g ave: %g\n\n", join( ', ',@$_ ), @r +esults; } __END__ P:\test>junk2 [ ] : Empty list at P:\test\junk2.pl line 5. [ 1, 2, 3, 4 ] min: 1 max: 4 ave: 2.5 [ 5, 1, 5, 6, 5 ] min: 1 max: 6 ave: 4.4 [ 1, 2, -0.1, 1e-005, 20000000000 ] min: -0.1 max: 2e+010 ave: 4e+009 [ fox dog ] : Non-numeric value(s) at P:\test\junk2.pl line 8.
You should probably use Carp::croak rather than die, a better regex (say from Regexp::Common) or better, Scalar::Util::looks_like_number() to detect non-numeric values.
And, if performance is your requirement, List::Util's calls, but make sure that you get a version that compiles the XS alternatives on your platform.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: minimum, maximum and average of a list of numbers at the same time
by polettix (Vicar) on Nov 10, 2005 at 15:46 UTC |