Functions

Global vs. Private Variables in Functions

By default, all variables mentioned in the outside program are recognized, may be used and may be modified inside the subroutine. i.e. by default, all variables in the program are global variables.

In the following program, we modify Example #1 from the previous slide so that average calculation inside the subroutine uses the value of the global variable $n.

Example #2

#!/usr/bin/perl

$a = 6;
$b = 10;

$n = 2;                        ##

$average = calc_average ($a, $b);
print "$average\n";

sub calc_average {

   my ($x, $y) = @_;
   my ($result);                ##

   $result = ($x + $y) / $n;    ##
   return $result;
}
 
# the program will print: 8

Notes:


Table of Contents.
Previous | Next.