http://qs321.pair.com?node_id=172938


in reply to Can't localize lexical variable $var at...

That's because...

...you can't localize a lexical variable. It doesn't make any sense.

A lexical variable has visibility limited by space: it is visible precisely within its scope, from the point of definition to the end of that block. It is known (except if shadowed) by its name throughout the scope, and it does not exist anywhere outside its scope. In particular, a sub outside the scope cannot see that variable.

Compare with a localized instance of a global variable. This has its visibility limited by time: it starts having its new value when local is executed, and continues with that value until execution of that block finishes. As such, to know its value you have to know about the particular execution path in effect. At different times, the same reference to a global variable may refer to totally different instances of it; a reference to a lexical variable always refers to the the same variable.

Consider a function (external to the scope) which uses a lexical <samp>$x</samp>. It always refers to the same <samp>$x</samp>, and calling code cannot change that. A function which uses a global <samp>$x</samp>, by contrast, refers to the current instance of <samp>$x</samp>; calling functions can change which instance that is.

Generally, global variables are useful for options. For instance, if your functions refer to a global variable $debug, you can turn on debugging for the entire program by saying "$debug=1" at the top. But you can also turn on debugging just for a small portion of the run by saying

{ local $debug = 1; # Code here prints debugging messages # ... } # Code here reverts to the old status
You can't do that (conveniently) with lexicals.

Mixing the 2 is (to mix a metaphor; sorry) mixing time and space; it just doesn't work.