in reply to exiting a for loop

Your code is very difficult to grasp for the following reasons. It is also failing for at least one of the following reasons:

Pass all variables and values into your subs through @_, not through global osmosis. Define your subs outside of the loop. Your final use of 'last' seems to be useless.

I may be missing the mark on scope closing around the subs after the first iteration of the loop, but if I'm right about that, there's your biggest problem. One of the very few legitimate reasons to use a variable from a broader scope within a sub is to set up an intentional closure. I don't think you're intentionally doing that. Instead, it's an unintentional consequence of the way you've got your code structured.


Dave

Replies are listed 'Best First'.
Re^2: exiting a for loop
by davido (Cardinal) on Mar 24, 2011 at 07:02 UTC

    Here is a simple example of the mistake you're making by defining the sub within a loop, and then using a loop-scoped variable as a global passing into the sub:

    use strict; use warnings; use Modern::Perl; for ( 1 .. 10 ) { my $iterator = $_; test(); sub test { say $iterator; } }

    The result printed is '1' on every iteration. This is because the sub can only be defined one time. That one time it's defined all the variables available to it will be cemented into place. The definition can not change even though the loop *appears* to be re-defining it. This means that the first iteration of the loop creates a closure around the sub, and only those variables available to it on the first iteration will be available to it ever.


    Dave

      Thanks so much for your advice. I had no idea I was creating a closure around my sub.