Writing Safe Code

An example program using my (I)

Let's look at a modified version of Example 3 from the Functions chapter, where we will calculate the average of the squares of a list of numbers. (We will see a more detailed example in the next slide)

Example

#!/usr/local/bin/perl

my @numbers = (2, 3, 4, 5);
my $ave2 = calc_ave_squares (@numbers);
print "Average: $ave2\n";

sub calc_ave_squares {

   my (@list) = @_;
   my ($no_of_elem, $result);
   my $sum = 0;

   $no_of_elem = scalar (@list);

   foreach $i (@list) {
      my $square = $i**2;
      $sum += $square;
   }

   $result = $sum / $no_of_elem;
   return $result;
}

Table of Contents.
Next.