Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: shift v. indexing into an array

by 7stud (Deacon)
on Nov 18, 2009 at 10:34 UTC ( [id://807885]=note: print w/replies, xml ) Need Help??


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:

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.

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://807885]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-20 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found