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 thanscalar
.y///c
is one char shorter thanlength
when getting the length of$_
.Need to iterate over the chars in
$_
? Replacesplit//,$_
with/./gs
. (Or use/./g
if you also want to skip newlines.) This works with other variables: replacesplit//,$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 withand
andor
, which do the same thing but with precedence lower than all other operators (including assignment). Loops can be done viamap
orgrep
. Even keywords likenext
,last
andreturn
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.