local
in Perl
Perl has a keyword, local
, for “localizing” variables, but in this case, local
isn't what most people think of as “local”. It gives a temporary, dynamically-scoped value to a global (package) variable, which lasts until the end of the enclosing block. However, the variable is visible to any function called from within the block.
To create lexical variables, which are more like the automatic variables discussed above, use the my
operator instead.
To understand how it works consider the following code:
$a = 1; sub f { local $a; $a = 2; g; } sub g { print "$a\n"; } g; f; g;this will output:
1
2
1
this happens since the global variable $a is modified to a new temporary (local) meaning inside f, but the global value is restored upon leaving the scope of f.
Using my
in this case instead of local
would have printed 1 three times since in that case the $a
variable is really local to the scope of the function f and not seen by g.
For this reason many consider that the operator local
should have had a different name like save
.
Read more about this topic: Local Variable