More on Passing Arguments to a Function

In the previous examples #1 and #2, arguments were passed to the function as a list of two individual variables.
$average = calc_average ($a, $b);
It is also possible to pass to the function an array, or a combination of array and scalar variables. Upon function invocation, the array will be decomposed to its elements, and then the list of variables and array elements will be assigned to the @_ special variable.

For example, let us modify the calc_average subroutine so that it will calculate the average of any given list of numbers. We will call the subroutine several times, each with different combination of arguments.

Example #3


# first case: passing individual scalar variables

$a = 8;
$b = 12;
$c = 13;

$ave1 = calc_average ($a, $b, $c);

print "First average: $ave1\n";

# second case: passing an array variable

@numbers = (5, 3, 1, 7);

$ave2 = calc_average (@numbers);

print "Second average: $ave2\n";

# start function definition

sub calc_average {

   my (@list) = @_;    # @_ is now assigned into an array variable
   #declaration and initialization of private subroutine variables, using my
   my ($no_of_elem, $result);
   my ($sum) = 0;      # declare and initialize in the same time

   # since we do not know in advance how many numbers will be passed to
   # the subroutine, we have to determine them from the number of elements
   # in the arguments list.

   $no_of_elem = scalar (@list);

   # iterate over the list of numbers passed to the function,
   # and calculate their sum.

   foreach $i (@list) {
      $sum += $i;
   #calculate average and return the result

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

# program output:   First average: 11
#                   Second average: 4

Table of Contents.
Previous | Next.