in reply to Re: exiting a for loop
in thread exiting a for loop

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

Replies are listed 'Best First'.
Re^3: exiting a for loop
by velocitymodel (Acolyte) on Mar 24, 2011 at 14:46 UTC

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