in reply to Use of uninitialized value in addition
1. You of course need a command loop.
What you should strive to do with a while() command loop is to put
the thing that ends the loop within the while()..that advice actually
goes for any while() loop!
The normal way in 'C' or Perl is to use the comma operator so that
the user prompt and the ending condition is all in one single
statement.
The main command loop "while" statement below does some "heavy lifting". The user is prompted, the input line from stdin is captured and it is checked against a variety of things: eg: D, d, done, DoNE. If one of those ends the loop, it is right there in the while() at the start of the loop. When using the comma operator, the true/false value is only dependent upon the last part of the statement.
2. A blank user line should be skipped.
3. There should be some validation of the user input and there is a line that does that. Maybe my regex is not perfect, but it is pretty close. Adjust this if needed.
4. Don't save stuff that is not need later. Use it now if you can. Here we just need the mean or average, so all we need is the total and the divisor - not the individual numbers as an array.
5. Oh, the chomp() in the errror message was needed because the "main line" code is independent of this line ending detail.
#!/usr/bin/perl -w use strict; my $total = 0; my $nums = 0; print "Average numbers: enter numbers then \"done\"\n"; while ( (print "Enter Number: "), (my $line=<STDIN>) !~ /^\s*d(?:one)?\s*$/i ) { next if $line =~ /^\s*$/; #re-prompt on blank lines if ($line !~ /^\s*((-?\d*)(\.\d*)?)\s*$/) #valid float { chomp($line); print "$line is not a valid number! Try again!\n"; next; } $total += $1; $nums++; } print "average is : ",$total/$nums,"\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Use of uninitialized value in addition
by GrandFather (Saint) on Mar 26, 2010 at 09:09 UTC | |
by Marshall (Canon) on Mar 30, 2010 at 03:06 UTC | |
by GrandFather (Saint) on Mar 30, 2010 at 03:52 UTC | |
by Marshall (Canon) on Mar 30, 2010 at 08:17 UTC | |
by ikegami (Patriarch) on Mar 30, 2010 at 04:16 UTC | |
by Marshall (Canon) on Mar 30, 2010 at 09:28 UTC | |
by ikegami (Patriarch) on Mar 30, 2010 at 14:41 UTC |