in reply to Re: shift v. indexing into an array
in thread shift v. indexing into an array
Also note that looping over a lexical variable declaration does not 're-declare' that variable. It just gets marked as uninitialized.
I was reading the Monk tutorial "Coping with Scoping", and I found an example which is relevant to this discussion:
That seems at odds with what you are saying. In any case, there are situations where declaring a my variable inside a loop can cause problems.Every time control reaches a my declaration, Perl creates a new, fresh variable. For example, this code prints x=1 fifty times:
for (1 .. 50) { my $x; $x++; print "x=$x\n"; }You get a new $x, initialized to undef, every time through the loop.
If the declaration were outside the loop, control would only pass by it once, so there would only be one variable:
{ my $x; for (1 .. 50) { $x++; print "x=$x\n"; } }This prints x=1, x=2, x=3, ... x=50.
|
|---|