"Perl for Perl Newbies" - Part 5 - Good Programming PracticesThe local keyword

6. The local keyword

Before Perl 5 came out and Perl got lexical scoping and the my keyword, an older local keyword was made available for programmers to temporarily "localise" the values of variables (or parts there of) in Perl.

As opposed to my, which is lexically scoped, local is dynamically scoped. What happens when one writes a local $myvar = NEW_VALUE_EXPR(); (which will work only for package variables) is that perl will store the previous value of the variable somewhere safe, allow the programmer to tamper with it as it pleases, and restore its value to its previous, saved state, when the block exits. As opposed to my, the new localised value will survive function calls in different functions.

So when should local be used?


Written by Shlomi Fish