Arrays

Examples for using the foreach construct - cont.

Calculate the sum of all array elements:

#!/usr/bin/perl

@measurement = (3, 2, 5, 9, 7, 13, 16);

$sum = 0;           #initialize a variable for the sum

foreach $i (@measurement) {
   $sum += $i;      #same as: $sum = $sum + $i
}

print "Sum is: $sum\n";

Table of Contents.
Previous | Next.