Introduction to Perl

Program format

Example

#!/usr/bin/perl

# A short program to find min, max, and average of a list of numbers.

@data = (43, 21, 98, 5, 17, 52, 110, 80);
$min = 10000;
$max = 0;
($sum, $number_of_items);

# Iterate over numbers

print "Calculations:\n";
foreach $n (@data) {
  $number_of_items++;                      # add 1 to number of items
  $sum += $n;                              # add $n to $sum
  if ($n > $max) {                         # find max
    print "$n was larger than $max\n";
    $max = $n;
  }                                        # find min
  if ($n < $min) {
    print "$n was smaller than $min\n";
    $min = $n;
  }
}

# Calculate average and display resutls

my $average = $sum / $number_of_items;      # calc average
print "\nResults:\n",                       # print results  
      "Data: ", join (", ", @data), "\n",   
      "Minimum: $min\n",
      "Maximum: $max\n",
      "Average: $average\n";

Table of Contents.
Previous| Next.