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:

foreach (@foo) { print $_; }

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:

foreach $bar (@foo) { print $bar; }

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:

foreach (@foo) { print; }

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. 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:

You should probably avoid using $_ there, and use a different, explicit variable instead. Your code might benefit from a little refactoring so that use of an implicit variable would help clarify things.

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)