http://www.perlmonks.org?node_id=832143


in reply to Re^2: Repeating Code - there has GOT to be a better way!
in thread Repeating Code - there has GOT to be a better way!

There is an excellent reason why you should always use my to declare a for loop variable in the loop - a for loop variable isn't what you think it is! Consider:

my $loopVar = 10; for $loopVar (1 .. 5) { print "$loopVar\n"; } print $loopVar;

What do you expect to see printed? What do you actually see printed? Now try this:

my $loopVar = 10; my @values = (0 .. 4); for $loopVar (@values) { ++$loopVar; } print "$loopVar, @values";

What do you expect to see printed? What do you actually see printed?

A for loop variable is aliased to each element of the for list in turn. When you use a previously declared variable as the loop variable you are really only using the name, the value is untouched.

So, always declare your for loop variable in the loop header because it ain't what you think it is anyway and declaring it make sure everyone gets that idea.

Note that a C style for loop is different and there it does often make sense to use a variable from the scope global to the loop.


True laziness is hard work