10.2. Making Variables Private to a FunctionProblemYour subroutine needs temporary variables. You shouldn't use global variables, because another subroutine might also use the same variables. Solution
Use sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once # ... } Discussion
The
Variables declared with
A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the
Because the parts of code that can see a
You can combine a my ($name, $age) = @ARGV; my $start = fetch_time(); These lexical variables behave as you would expect a local variable to. Nested blocks can see lexicals declared in outer blocks, but not in unrelated blocks: my ($a, $b) = @pair; my $c = fetch_time(); sub check_x { my $x = $_[0]; my $y = "whatever"; run_check(); if ($condition) { print "got $x\n"; } }
In the preceding code, the Don't nest the declaration of named subroutines within the declarations of other named subroutines. Such subroutines, unlike proper closures, will not get the right bindings of the lexical variables. Recipe 10.16 shows how to cope with this restriction.
When a lexical goes out of scope, its storage is freed unless a reference to its value's storage space still exists, as with sub save_array { my @arguments = @_; push(@Global_Array, \@arguments); } Perl's garbage collection system knows not to deallocate things until they're no longer used. This is why we can return a reference to a private variable without leaking memory. See AlsoThe section on "Scoped Declarations" in Chapter 2 of Programming Perl and the section on "Private Variables via my( )" in perlsub (1) |
|