Tinkering with Perl

Jonathan's Corner (Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  45  46  47  48  49  50  51  52  53  54  Next  Skip Forward 
Printer-Friendly Version

Running average

This program reads numbers and tells their running average:

#!/usr/bin/perl -w
$total = 0;
$number_of_items = 0;
$result = 0;
while(1) # 1 is always true.
    {
    print "Next item: ";
    $input_line = <>;
    chomp $input_line;
    $total = $total + $input_line;
    ++$number_of_items;
    $result = $total / $number_of_items;
    print "The average so far is " + $result + ".\n";
    }

See also:

Sample programs - Friends and pets

Tinkering with Perl is a free book that provides an introduction to programming in Perl, as well as a basic reference for things like foreach in Perl, if-then, and if-then-else, in addition to providing a glossary where you can find definitions for concatenate and other terms.

Tinkering with Perl may be one of the most popular offerings on this site, but it's not the only attraction. You can read a tongue-in-cheek Game Review: Meatspace, read an even more offbeat customer service survey (whether or not you actually fill it out), and spend a few minutes wishing your boss would read, The Administrator Who Cried, "Important!" (Not to mention that there are other things you can read here besides tech stuff, from Janra Ball: The Headache to The Spectacles.)

Read more...

Top

Jonathan's Corner (Search & Sitemap) > Writing > Miscellaneous Nonfiction > Tinkering with Perl
Skip Back  Previous  45  46  47  48  49  50  51  52  53  54  Next  Skip Forward 
Printer-Friendly Version