[EMAIL PROTECTED] wrote: > Hi, > With regards to the script below, can somebody explain to me why > testcounter after counting 1,2,3, remains at 3 all the time. I thought > it would have been reset to zero by the outer while loop. > Thanks > > #!c:\perl\bin\perl > use strict; > my $anything = 5; > my $counter =0; > > while ($anything > $counter){ > my $testing = 3; > my $testcounter = 0; > $counter += 1; > > while ($testing > $testcounter ){ > $testcounter += 1; > test() if (1); > > sub test { > print "$testcounter.\n\n"; > } > } > }
The statement my $testcounter = 0; will create the variable and initialize its value to zero. Ordinarily the variable will be released at the end of the loop and recreated (and initialized) when the loop starts again, but since you have declared a subroutine that references the variable, its reference count never goes to zero and it is never released, and so never reinitialized. This construct is called a closure, and can be useful if you understand it, but here it is simply causing problems. If you always declare your subroutines at file scope then you will avoid this. Look at the program below to see how. HTH, Rob use strict; use warnings; my $anything = 5; my $counter = 0; while ($anything > $counter) { my $testing = 3; my $testcounter = 0; $counter += 1; while ($testing > $testcounter ) { $testcounter += 1; test($testcounter); } } sub test { my $n = shift; print "$n.\n\n"; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/