Use of 'local'
Posted on 2008-06-11
It seems that the 'local' keyword isn't used much in perl 5. I just wanted to double-check if my understanding of it is correct.
When you declare a local variable, it replaces the value of a global variable of the same name, until the scope in which is was used is exited, and then it will return the variable back to its global value.
our $g = 5;
local $g = 10;
So the above is going to print:
That's because g, a global, is set to 5 initially. Inside a(), it is re-scoped as a local. So the global value of $g is 'put on the side' temporarily. Now anytime I use $g inside a() or any scope called within a(), it's going to appear as if $g is 10?
Finally when I exit the scope of a(), $g is restored to its original value of 5.
Is that right? It seems like a confusing method.