Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by sundialsvc4 (Abbot)
on Jul 22, 2014 at 12:06 UTC ( [id://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 "$_"

Replies are listed 'Best First'.
Re^2: foreach loop and creating files with "$_"
by BillKSmith (Monsignor) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1094621]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-18 04:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found