PBP: 058 Dollar-Underscore

Mr. Conway suggests that you be wary of any modification to $_.  Personally, I take it further than that, and try never to use the thing at all.

The PBP suggests that modifying $_ can have unexpected side effects, as $_ is often an alias to some other variable which no one was expecting to be changed.  It provides good succinct examples, so I won’t reproduce them here.

I go further than this.  I almost never use $_.  I never use it in the implicit case, where you don’t specify the variable being operated on.  I consider this a Perl misfeature; the defaulting to $_ just makes mysterious, hard to read code with strange side effects.  Specify which variable you’re using.  When possible, create a lexical and use that.

$_ is part of Perl’s line noise, and it’s likely to cause action at a distance.  It’s also likely to be used by accident if you miss an operation, so you’ll chop, substitute, or translate the wrong thing.  I avoid it.

One of the reasons I dislike map and grep is that you must use $_.  I do use it there, as it is not usually worth creating a variable and assigning it in those tight loops.  If it is that complicated, I’ll move it to a function, and call the function instead.


One Response to “PBP: 058 Dollar-Underscore”

  1. Jay Allen says:

    “If it is that complicated, I’ll move it to a function, and call the function instead.”

    …which, in and of itself should be a PBP (I’m surprised it wasn’t!). Map/grep and other syntaxes which use the block syntax should be very short and EASILY understandable, otherwise, they detract from readability. Keep up the good work!

Leave a Reply