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.


True laziness is hard work

In reply to Re: Use of uninitialized value in addition by GrandFather
in thread Use of uninitialized value in addition by Solarplight

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.