go ahead... be a heretic | |
PerlMonks |
a rule of thumb for $_ in Perlby apotheon (Deacon) |
on Oct 01, 2007 at 21:05 UTC ( [id://641994]=perlmeditation: print w/replies, xml ) | Need Help?? |
Disclaimer: This is my opinion. It doesn't have to be yours. I do not claim to speak for the Perl community as a whole in this regard. Perl makes use of an implicit scalar variable, $_. The $_ variable is assigned a value whenever you write code that requires a scalar value to be passed to something without actually passing it explicitly. For instance, if the first line of your foreach loop looks like this: foreach (@foo) {. . . you're going to get each element of @foo being available to the code executed inside the loop, one iteration at a time, in the $_ variable. As such, you might write code like this:
Let's ignore for the moment that you could, with a very simple loop like that, put the print part before the foreach part, all on one line, and skip the braces entirely. It’s 'just a bit of very simple example code. Anyway . . . a lot of people find $_ ugly and even obfuscatory. The answer for most is to always avoid $_ at all costs. Some even take that to the unreasonable extreme of avoiding Perl, as if the entire language is tainted by their personal distaste for the $_ variable. In the case of continuing to use Perl while avoiding $_, however, you might end up with code like this:
This way, you can name your iterator scalar descriptively, clarifying the code. I absolutely agree that this is an excellent approach to take — but I also believe there are times that the inclusion of the $_ variable in the Perl language can provide some benefits, not only for the coder, but for whoever has to read the code again later. The key is that you should never have to actually type the dollar and underscore characters to access that variable's contents. You could, for instance, do this:
That is the sort of behavior that makes it possible for a Perlist to do things like print foreach @foo;, in fact — which can add even more clarity to your code when the contents of your loop consist of a single (short) line of code. Just remember, when dealing with Perl, that $_ is an implicit variable, and should only be used implicitly (if at all possible to avoid explicit use). When the code in your loop (or wherever else you are using $_, whether you use it explicitly or implicitly) is brief enough, consider whether implicit use of $_ would clarify your code. If it wouldn't, or you basically can't use it with your code as written, consider whether one of the following is true:
In other words, the rule of thumb for $_ in Perl is as follows: If you have to use it explicitly, use something else instead. That rule of thumb is not just "never use it". It's there for a reason. (NOTE: crossposted)
Back to
Meditations
|
|