in reply to Problem understanding why for loop won't work when foreach is working

If you do not know what a closure is, the following explanation probably won't help much.

  1. With the C-style for loop, the subroutine sub{ print "Test $i \n"; } is closing over the variable $i.

    That is, the value of the variable within the string is not interpolated until the subroutine is run, and by the time it is run, $i retains the last value it had when the loop completed -- Ie. 10 -- for all instances of the subroutine.

  2. With the foreach-style for loop; the subroutines are closing over aliases to the values produced by the range operator in the for loop.

    Thus each instance of the subroutine is closing over an alias to a different constant value, 1 .. 10.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
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.