Difference between revisions of "local (Perl function)"
Jump to navigation
Jump to search
m (local var preserves/ignores globals of the same name) |
|||
Line 3: | Line 3: | ||
* within any further curly braces that are within that current set (as one would expect) | * within any further curly braces that are within that current set (as one would expect) | ||
* within any functions called from within the current set of curly braces (or from within any others nested inside that); this is called "dynamic scoping" | * within any functions called from within the current set of curly braces (or from within any others nested inside that); this is called "dynamic scoping" | ||
+ | |||
+ | If a variable of the same name exists outside of the current scope, {{perlfunc|local}}() creates a new variable and ignores/preserves the older variable. ''Query: is there a way to access the older variable from inside this scope?'' The older variable is once again accessible when execution leaves {{perlfunc|local}}()'s defined scope. | ||
{{perlfunc|local}}() is very similar to {{perlfunc|my}}(), except that {{perlfunc|my}}() does not do dynamic scoping. {{perlfunc|my}}() is generally recommended over {{perlfunc|local}}(). (You may hear the saying "Don't use local()" from experienced Perl programmers.) | {{perlfunc|local}}() is very similar to {{perlfunc|my}}(), except that {{perlfunc|my}}() does not do dynamic scoping. {{perlfunc|my}}() is generally recommended over {{perlfunc|local}}(). (You may hear the saying "Don't use local()" from experienced Perl programmers.) |
Revision as of 17:51, 7 April 2006
The built-in function local() in Perl creates a variable that is local to the current scope and any functions called from within that scope. That is, it is defined:
- within the current set of curly braces {}
- within any further curly braces that are within that current set (as one would expect)
- within any functions called from within the current set of curly braces (or from within any others nested inside that); this is called "dynamic scoping"
If a variable of the same name exists outside of the current scope, local() creates a new variable and ignores/preserves the older variable. Query: is there a way to access the older variable from inside this scope? The older variable is once again accessible when execution leaves local()'s defined scope.
local() is very similar to my(), except that my() does not do dynamic scoping. my() is generally recommended over local(). (You may hear the saying "Don't use local()" from experienced Perl programmers.)
Examples
- local($avar,$anothervar);
- local($arg1,$arg2) = @_;
- local(%hashvar);
- local %anotherhash;
- local $justonevar;
- local @anArray;