in reply to Re^2: Scope and references
in thread Scope and references

I never realized that a simple loop like this ... actually allocated and destroyed a new array every time through the loop. Since you go around the loop twice, it seems like you don't "leave" the scope in which @a was delcared, so @a should still "be there" during the second iteration. I still don't get that.

In for(...) { ... } the curly braces define a block. Each time the loop iterates you re-enter that block. And every time you enter a block, you enter a new scope.

That is just the way it is, and the way it is meant to be.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^4: Scope and references
by {}think (Sexton) on Jun 19, 2011 at 18:44 UTC

    That was it!

    for (my $i=0; $i <=1; $i++) { #new scope in brkts }
    I had always thought of the FOR loop as a single construct. I didn't realize that each time the control logic ($i++, etc.) is exectuted, you EXIT the brackets and lose that scope! But if you parse the code very precisely, that is literally what happens, so it now makes sense! Thank you BrowserUk!
    {}think; #Think outside of the brackets
Re^4: Scope and references
by {}think (Sexton) on Jun 22, 2011 at 02:33 UTC
    So here was my misconception:
    I thought that the scope of a for loop was
    foreach (@a) { |<==From HERE to HERE==>| }
    and that you just bounced aroud INSIDE OF the brackets. But I guess every time you evaluated the control statement, you leave the brackets and you lose scope and re-enter it. I did read Coping with Scoping, and that deals with this exact situation.
    {}think; #Think outside of the brackets
      Hello {}think
      $ perl -e " {}think; #Think outside of the brackets " Bareword found where operator expected at -e line 1, near "}think" (Missing operator before think?) syntax error at -e line 1, near "}think" Execution of -e aborted due to compilation errors.
      Nice try :)