Skip to main content
4 of 4
Disentangle confusion with `$_` and `$x` in advice on `split`.
breadbox
  • 7.2k
  • 31
  • 44

TMTOWTDI

That's the most important Perl golfing tip you need to know. Whenever you're looking at some too-long sequence of characters you absolutely have to have in order to accomplish your task, ask yourself if there isn't some other way to get the same effect using a different feature. There usually is. Here are just a handful:

  • ~~ enforces a scalar context and is 4 chars shorter than scalar.

  • y///c is one char shorter than length when getting the length of $_.

  • Need to iterate over the chars in $_? Replace split// with /./gs. (Or use /./g if you also want to skip newlines.) This works with other variables: replace split//,$x with $x=~/./gs.

  • Every Perl builtin returns something. print returns 1, for example, to indicate successful I/O. If you need to initialize $_ to a true value, for example, $_=print$foo allows you to kill two birds with one stone.

  • Almost every statement in Perl can be written as an expression, allowing it to be to used in a wider variety of contexts. Multiple statements can be become multiple expressions chained together with commas. Tests can be done with short-circuiting operators ?: && ||, and also with and and or, which do the same thing but with precedence lower than all other operators (including assignment). Loops can be done via map or grep. Even keywords like next, last and return can be used in an expression context, even though they don't return! Keeping these kinds of transformations in mind give you opportunities to replace code blocks with expressions that can be stuffed into a wider variety of contexts.

breadbox
  • 7.2k
  • 31
  • 44