Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: foreach loop and creating files with "$_"

by sundialsvc4 (Abbot)
on Jul 22, 2014 at 12:06 UTC ( #1094621=note: print w/ replies, xml ) Need Help??


in reply to foreach loop and creating files with "$_"

I’d go with foreach my $var (1..5) every time, for the very same reason that “I don’t like to see the same global variable-name being used again and again.”   Especially not, as in this case, one that you can’t see.

Okay, so it works okay now.   Goody,goody, but then someone comes along and needs to make a truly-slight change ... which just happens to consist of some other control-structure that changes the meaning and value of $_.   Now, they have to dance-around your program, making a bunch of source-code changes (entirely unrelated to what they wanted to do ...), just to do what you could well have done the first time.   (And, to keep things realistic, let’s say they inadvertantly miss just one thing ...)   Meh.   That sort of thing is “just not worth the clever.”

Keep it simple ... keep it maintainable.   I’m not laying-down any sort of commandment here, but it is trivially easy (as shown) to create a very nice, named, locally-scoped variable, associated with the loop and existing only within its scope, that contains the value of the loop index.   That’s one of Perl’s nicest, most pragmatically useful features.   (As is $_, yes, in small doses ...)


Comment on Re: foreach loop and creating files with "$_"
Re^2: foreach loop and creating files with "$_"
by BillKSmith (Chaplain) on Jul 22, 2014 at 15:13 UTC
    I think the biggest maintainability problem with $_ is accepting it as a default without using it. We are forced to remember every place it can be used in this way.
    Bill

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (10)
As of 2014-12-21 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (105 votes), past polls