Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

by Your Mother (Canon)
on Mar 31, 2010 at 17:57 UTC ( #832107=note: print w/ replies, xml ) Need Help??


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

Tangent: danger sign-

foreach [where is the my?] $cmd (keys %<name>Cmd) {

You should always be using strict. It will save you hours and hours leading to days and even weeks of effort over time.


Comment on Re: Repeating Code - there has GOT to be a better way!
Download Code
Re^2: Repeating Code - there has GOT to be a better way!
by jedikaiti (Friar) on Mar 31, 2010 at 18:04 UTC

    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

      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

      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://832107]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2014-10-01 00:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (386 votes), past polls