in reply to problem with variable scoping

Is it always zero at the beginning of the loop body, or on every other iteration?  In case of the latter, it could be because the conditions you're testing are such that $i gets decremented in the elsif branch every time it has become 1.  Heavily simplified, like this:

my $i=0; foreach my $field (qw(foo bar baz quux)) { print "i=$i\n"; if ($i == 0) { $i++; # increment } elsif ($i == 1) { if (0) { if (0) { $i--; } } else { $i--; # decrement } } } __END__ i=0 i=1 i=0 i=1