.... it creates a kind of global variable with restricted scope! If this is in a subroutine, the second time you call the sub, you get exactly the same array, not a new one.
This is not true. Look at the following:
use strict; use warnings; sub mytest { my $var if 0; $var++; print $var, "\n"; } mytest(); mytest(); __OUTPUT__ 1 1
We see several important things in that snippet. First, there are NO errors under strictures, and no warnings. Second, $var is NOT the same variable each time mytest() is called. If we had created a closure, the output would have been 1 and 2, not 1 and 1. If we had autovivified a global, we would have gotten a strictures error, or at minimum, the output would have been 1 and 2. But none of that happens. We get a new lexical variable each time mysub() is called.
Why?
Because my has two elements to how it works. First, the compiletime side. At compiletime, the framework is made for a lexical variable. Yet at compiletime, it is too soon to know the outcome of program logic. So the lexical is created without any regard for logic; all that matters is lexical scope.
At runtime, logic springs to life. And if the "my" declaration has an assignment component to it, as in my $x = 10 if $condition; that assignment will only take place if $condition is true. But $x exists within the lexical block whether or not $condition is ever true. And it falls out of scope just like any good lexical would, when the lexical block ends, even if its a subroutine.
Dave
In reply to Re: Re: declaring same variable
by davido
in thread declaring same variable
by samy1212
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |