Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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

by jedikaiti (Friar)
on Mar 31, 2010 at 18:04 UTC ( #832112=note: print w/ replies, xml ) Need Help??


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

Yes, I am using strict, and the "my $cmd;" line actually appears further up the code. Unless there's a good reason not to, in which case I will happily change it!

Kaiti
Swiss Army Nerd


Comment on Re^2: Repeating Code - there has GOT to be a better way!
Re^3: Repeating Code - there has GOT to be a better way!
by Your Mother (Canon) on Mar 31, 2010 at 18:55 UTC

    Great. It's best to restrict it to the smallest possible scope. Having it at the top makes it, more or less, a global which can be seen or persist anywhere in the script. This can lead to lame/long debugging sessions. Better to put it inline with the loop.

      Gotcha - thanks!

      Kaiti
      Swiss Army Nerd
Re^3: Repeating Code - there has GOT to be a better way!
by GrandFather (Cardinal) on Mar 31, 2010 at 20:14 UTC

    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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2014-07-12 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (241 votes), past polls