Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by jedikaiti (Hermit)
on Mar 31, 2010 at 18:04 UTC ( [id://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!

Replies are listed 'Best First'.
Re^3: Repeating Code - there has GOT to be a better way!
by GrandFather (Saint) 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
Re^3: Repeating Code - there has GOT to be a better way!
by Your Mother (Archbishop) 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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-04-16 17:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found