Dynamically Scoped Variables: local
Using a local operator
on a global variable gives it a temporary value each
time local is executed, but it
does not affect that variable’s global visibility. When the program
reaches the end of that dynamic scope, this temporary value is
discarded and the original value is restored. But it’s always still
a global variable that just happens to hold a temporary value while
that block is executing. If you call some other function while your
global contains the temporary value and that function accesses that
global variable, it sees the temporary value, not the original one.
In other words, that other function is in your dynamic scope, even
though it’s presumably not in your lexical scope.[83]
This process is called dynamic scoping
because the current value of the global variable depends on your
dynamic context; that is, it depends on which of your parents in the
call chain might have called local. Whoever did so last before calling
you controls which value you will see.
If you have a local that
looks like this:
{
local $var = $newvalue;
some_func();
...
}you can think of it purely in terms of runtime assignments:
{
$oldvalue = $var;
$var = $newvalue;
some_func();
...
}
continue {
$var = $oldvalue;
}The difference is that with local the value is restored no matter how
you exit the block, even if you prematurely return from that scope.
As with my, you can
initialize a local with a copy of the same global variable. Any changes to that variable during the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access