introduction to web programming Variable Localization In Perl 4 there were two ways to define the package scope of a variable. First, the variable might have global scope.

Global scope means that the variable could be seen (accessible/modifiable) by every other object in the program. Sometimes this is a good thing. Sometimes you have variables, for example, whose values are relevant to every aspect of your program.

However, most times, it is better to limit the scope of variables to specific areas in your program. Limiting the scope helps maintain name space, reduce programmatic complexity, and increase modularity of design.

To limit package scope, Perl initially provided the "local" keyword. The local keyword was used to limit the scope of a variable to within its enclosing brackets

Consider the following example. Notice that when the local keyword is applied to the variable $a, changes made to $a inside of the subroutine have no affect on the value of $a outside of the subroutine. On the other hand, $b is not declared local in the subroutine and hence, changes made to $b in the subroutine affect $b outside of the subroutine:

[Localization Example]

In Perl 5, localization is handled by the "my" keyword which hides the variable from the outside world completely.

Hey, isnít that what local was supposed to do?

Well, not exactly. The local keyword is meant to assure "dynamic" scoping whereas the "my" keyword is for "lexical" scoping.

The big difference is that dynamically scoped variables are visible not only from within the enclosing brackets but in all subroutines called within those brackets. Lexical variables are totally hidden. Consider the following examples. Notice in particular that when "my" is applied to $a, the second subroutine cannot see the change whereas when "local" is applied, it can.

[Localization Example 2]

[Localization Example 3]

Previous | Next | Table of Contents