Tips for golfing in Perl? What general tips do you have for golfing in Perl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Perl (e.g. "remove comments" is not an answer). Please post one tip per answer.
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 ?: &amp;&amp; ||, 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.