in reply to Re: Difference between for and foreach
in thread Difference between for and foreach

I've been caught out in the past by expecting to be able to rely on changes to the loop variable being preserved once the loop has terminated. For example, perhaps you want to know at which iteration a foreach loop terminated early using a last. However, the loop variable is localised inside the loop so that it reverts to it's old value after the loop.

$ perl -Mstrict -Mwarnings -le ' > my $x = 0; > print $x; > for $x ( 1 .. 10 ) > { > my $y = rand; > print qq{$x -- $y}; > last if $y > 0.85; > } > print $x;' 0 1 -- 0.820319728766666 2 -- 0.070987764836417 3 -- 0.632845876776752 4 -- 0.195428179899814 5 -- 0.847997411282524 6 -- 0.353572570937089 7 -- 0.865375393672675 0 $

You have to preserve the loop variable from inside the loop if you need to access it afterwards.

Cheers,

JohnGG