8.5 Private Variables in Functions
We've already talked about the sub add { my ($sum); # make $sum a local variable $sum = 0; # initialize the sum foreach $_ (@_) { $sum += $_; # add each element } return $sum; # last expression evaluated: sum of all elements }
When the first body statement is executed, any current value of the global variable 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 } What if we wanted all elements greater than 50 rather than greater than 100? We'd have to edit the program, changing the 100's to 50's. But what if we needed both? Well, we can replace the 50 or 100 with a variable reference instead. This makes it look like: sub bigger_than { my($n,@values); # create some local variables ($n,@values) = @_; # split args into limit and values my(@result); # temporary for holding the return value foreach $_ (@values) { # step through the arg list if ($_ > $n) { # is it eligible? push(@result,$_); # add it } } return @result; # return the final list } # some invocations: @new = bigger_than(100,@list); # @new gets all @list > 100 @this = bigger_than(5,1,5,15,30); # @this gets (15,30)
Notice that this time we used two additional local variables to give
names to arguments. This is fairly common in practice; it's much easier to talk about
The result of
my($n,@values); ($n,@values) = @_; # split args into limit and values with: my($n,@values)= @_; This is, in fact, a very common Perl-ish thing to do. Local nonargument variables can be given literal values in the same way, such as: my($sum) = 0; # initialize local variable
Be warned that despite its appearances as a declaration,
|
|