Subject: | Illegal division by zero when working on empty set |
I know you should never try to get an average for an empty dataset, but
sometimes a program may fail to fill it. In this case, perhaps it should
return undef or maybe 0? I believe that would be better than getting an
"Illegal division by zero" error.
My patch for the avg method follows:
sub avg
{
my $self = shift;
my $total = 0;
my $length = $self->length;
if (!$length) return undef; # return undef on empty vector
for my $i (0..$length - 1) {
my $v = $self->{data}->[$i];
if (ref($v) && $v->can('value')) {
$total += $v->value;
} else {
$total += $v;
}
}
return $total / $length;
}