Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^3: Repeating Code - there has GOT to be a better way!

by GrandFather (Cardinal)
on Mar 31, 2010 at 20:14 UTC ( #832143=note: print w/ replies, xml ) Need Help??


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


Comment on Re^3: Repeating Code - there has GOT to be a better way!
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://832143]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2014-07-29 22:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (229 votes), past polls