Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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 "$_"

Replies are listed 'Best First'.
Re^2: foreach loop and creating files with "$_"
by BillKSmith (Vicar) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1094621]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2018-04-27 03:08 GMT
Find Nodes?
    Voting Booth?