in reply to Use of uninitialized value in addition
Perl provides a a lot of leverage for this sort of program. Because arrays are dynamic and report the number of elements they contain you seldom need a separate counter. In many places you can use statement modifiers to make short work of small loops and eliminate extra temporary variables. Almost always if you are looping over the elements of an array you don't need to index into the array. So, taking those techniques into account, and adding a missing layer of error checking, consider the following:
#!/usr/bin/perl use strict; use warnings; print "Mean Average Program\n"; my @values; push @values, $_ while (defined ($_ = nextValue ())); my $sum; $sum += $_ for @values; my $mean = $sum / @values; print "\nThe mean of your values is $mean\n"; sub nextValue { print "Enter a value ('done' if finished): "; while (1) { chomp (my $value = <>); return if $value =~ m'done'i; return $value if $value =~ /[+-]?\d+(\.\d*)?([+-]?[eE]\d+)?/; print "I don't recognise $value as a number or as 'done'. Try +again: "; } }
given the input 2, 2, 3, done prints:
Mean Average Program Enter a value ('done' if finished): 2 Enter a value ('done' if finished): 2 Enter a value ('done' if finished): 3 Enter a value ('done' if finished): done The mean of your values is 2.33333333333333
Note that the repeating prompt and error checking checking code are in a sub which returns undef to terminate the data collection loop or a valid number otherwise - no bogus strings used as numbers here thank you very much.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Use of uninitialized value in addition
by Solarplight (Sexton) on Mar 26, 2010 at 17:07 UTC |