Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

$_ is not just a kid's toy.

Let's say I'm talking to a human programmer. I say, "Read in a line of text. If it ends in a newline, remove the newline." Cool.

But when I talk to a computer, I can't talk that way. It says, "If what ends in a newline?" It doesn't understand "it".

Except in Perl. In Perl, $_ is "it". It's what we're talking about if I don't specify something specific. It's where the line of text gets read into if I don't specify a destination. It's where the newline gets removed from if I don't specify a variable. It lets me ignore specifics when I don't care about those specifics. It makes Perl much closer to how we talk to each other instead of how we talk to computers.




It’s also where you (or your adhd colleague, or future self) introduce a subtle bug if one of your subs reads another stream and you forgot to local $_ in it. And you realize that you don’t always understand what “it” is either and that it is a bad idiom for formal systems. Isn’t worth it in the long run, especially in implicitness-ridden code that perl encourages. Write out your “line” and assign it back:

  if (line ~= /\n$/) {
    line = chop(line)
  }
Or use a library with helper functions akin to chomp(). This sentence-like code with $_ is a sign of wrong level of abstraction which solves small tasks with smaller components. If a language claims text processing capabilities, it should provide a function or a generator that does “read this <enc=utf-8> file and split by <what>[ omitting empty ones but keeping original line numbers in the emitted records][ also erase /\s*#.*$/-comments][ keep original lines too]” among other common tasks. All this $, $. $/ $_ could be just a couple of functions that accept a config argument with few optional callbacks for custom needs. You don’t have to create a whole language to read lines split by newline then by separator. Same for matching vars, could be just a sliding context arg to a properly designed matching api.

You may argue that other languages don’t have it either, well that’s true. Standard libraries usually suck compared to what perl does out of box.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: