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/local/bin/perl
$a = 6;
$b = 10;
$n = 2; ##
$average = calc_ave ($a, $b);
print "$average\n";
sub calc_ave {
my ($x, $y) = @_;
my ($result); ##
$result = ($x + $y) / $n; ##
return $result;
}
# the program will print: 8
Notes:
- If $n
was declared inside the subroutine as a private variable
with the my operator, e.g.
my ($result, $n);
$n would not have retained
its value from the program (namely 2),
but would have been recreated with an undef value, and upon program
execution we would have got an error message: "Illegal division by zero".
- Why, then, bother passing $a
and $b
as arguments and not using them as global variables?
- We might wish to call (invoke) the
calc_ave subroutine many times
in the same program, each time with different arguments.
- Subroutines are optimally written as modular, independent units,
so that they can be placed in any program we wish and do not rely on /
interfere with that program's variables.
- It is recommended to avoid using global variables as much as possible.
Try to rewrite Example #2 such that $n
will be passed to the calc_ave
function as an argument.
Table of Contents.
Next.