Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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 avoiding work at the Monastery: (6)
As of 2014-08-30 23:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls