#!/usr/bin/perl -w ################################################################ # # Corpus Analysis and Programming, Homework #3. # # Source: PerlHTP, Exercise 3.11. # # Programmed by William Yeh, 2002/09/26. # ################################################################ # # first, we declare several variables to hold the state... # $count = 0; # number of numbers input so far $sum = 0; # the sum of all integers so far # $largest; # later we'll use this variable to hold the largest one # $smallest; # later we'll use this variable to hold the smallest one print "Please input a series of numbers...\n"; # # now we enter the main loop of the whole program... # while ($data = ) { chomp $data; next if length($data) < 1; # skip this item if empty line # the keyword "next" is to be explained in Chapter 5. ++$count; # increment the counter $sum += $data; # calculate the new sum if ($count == 1) { # special case: this is the 1st input! $largest = $smallest = $data; } elsif ($data > $largest) { $largest = $data; } elsif ($data < $smallest) { $smallest = $data; } # NOTE: Since the 3 conditions above are mutually exclusive, # we do not program in the following less efficient (but still correct) way: # # if ($count == 1) { # special case: this is the 1st input! # $largest = $smallest = $data; # } # else { # general case # $largest = $data if ($data > $largest); # $smallest = $data if ($data < $smallest); # } } if ($count < 1) { # no input print "Sorry, no input at all.\n"; } else { $average = $sum / $count; print "Total number of input: $count\n", "The largest: $largest\n", "The smallest: $smallest\n", "The average: $average\n"; }