Private Variables in Functions
We’ve already talked about the @_ variable
and how a local copy gets created for each subroutine invoked with
parameters. You can create your own scalar, array, and hash variables
that work the same way. You do this with the my
operator, which takes a list of variable names and creates
local versions of them (or
instantiations, if you like bigger words).
Here’s that add function again, this time
using my:
sub add {
my $sum; # make $sum a local variable
$sum = 0; # initialize the sum
foreach $_ (@_) {
$sum += $_; # add each element
}
return $sum; # last expression evaluated:
# the sum of elements
}When the first body statement is executed, any current value of the
global variable $sum is saved away, and a brand
new variable named $sum is created (with the value
undef).
When the subroutine exits, Perl discards the local variable and
restores the previous (global) value. This method works even if the
$sum variable is currently a local variable from
another subroutine (a subroutine that invokes this one, or one that
invokes one that invokes this one, and so on). Variables can have
many nested local versions, although you can access only one at a
time.
Here’s a way to create a list of all the elements of an array greater than 100:
sub bigger_than_100 { my (@result); # temporary for holding the return value foreach $_ (@_) { # step through the arg list if ($_ > 100) { # is it eligible? push(@result,$_); # add it } } return @result; # return the final list ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access