Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question

13 Answers 13


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//,$x with $x=~/./gs. (Or use $x=~/./g if you also want to skip newlines.)

  • 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.

share|improve this answer

Use $_ to eliminate scalar references. It is the special variable that is used as a default by most functions, and just leaving out parameters is a shortcut to reference this variable.

By changing $n to $_, you can change $n=<>;chop$n;print$n to $_=<>;chop;print

Here, the print function prints the contents of $_ by default, and chop also works on $_.

share|improve this answer
Is $_=<>; required, doesn't <>; read the line into $_ automatically? –  sundar Aug 20 '13 at 18:55
No, I don't think so. I compared the programs $_=<>;print and <>;print. The first one repeats back to me what I type, while the other one doesn't. –  PhiNotPi Aug 21 '13 at 21:22
Oh, thanks, turns out that happens only in cases like print while(<>). Not sure if it's a special case or there's some coherent logic behind it, neither <>'s part in perlop nor while part of perlsyn seem to mention this behaviour. –  sundar Aug 21 '13 at 22:36
@sundar while(<>) is a special case, documented in perlsyn, I/O Operators: 'If and only if the input symbol is the only thing inside the conditional of a "while" statement (even if disguised as a "for(;;)" loop), the value is automatically assigned to the global variable $_, destroying whatever was there previously." –  kernigh Nov 9 '14 at 0:22

Use Perl's special variables where-ever you can, eg:

  • Use $" instead of " "
  • Use $/ instead of "\n"

They have the added benefit of being a guaranteed one-character long identifier, with help from the lexer. This makes it possible to glue it to the keyword following it, as in: print$.for@_

The list of all the special variables is available here: Special Variables

share|improve this answer

Abuse Perl's special variables!

  • As noted in a previous answer $/ and $" are initialized by default to "\n" and " ", respectively.

  • $, and $\ are both set to undef by default, and are 3 chars shorter.

  • Setting $\ to a value will cause it to be appended to every print. For example: perl -ple '$\="=".hex.$/' is a handy hex-to-decimal converter.

  • If you're not reading files from the command-line, you can use the -i command-line switch as an extra channel for inputting a string. Its value will be stored in $^I.

  • $= forces whatever is assigned to it to be an integer. Try running perl -ple '$_=$==$_' and giving it various inupts. Likewise, $- forces its value to be a non-negative integer (i.e. a leading dash is treated as a non-numeric character).

  • You can use $. as a boolean flag that is automatically reset to a true (nonzero) value on every iteration of a while(<>) loop.

share|improve this answer

Use statement modifiers instead of compound statements.

Compound statements tend to require parentheses for the argument and braces for the block, whereas statement modifiers need neither.


  • $a++,$b++while$n-- vs while($n--){$a++;$b++}
  • chop$,if$c vs if($c){chop$,}

Note that the last example ties with $c&&chop$,, but starts really shining for most multi-statement operations. Basically anything that loses operator precedence to &&.

share|improve this answer

I'm sure some of these have formal names and I'm just not aware of them.

  • If you have a while loop (or a for loop you can make into a while loop) you can define the "while" after the command: print $n++ while ($n < 10)
  • If you need to read everything from STDIN into a string: $var = join('',<>)
  • As CeilingSpy pointed out, using $/ instead of \n is faster in some situations: print ('X'*10) . "\n"; is longer than print ('X'*10) . $/;
  • Perl's say function is shorter than print, but you'll have to run the code with -E instead of -e
  • Use ranges like a..z or even aa..zz. If needed as a string, use join.
  • Incrementing strings: $z = 'z'; print ++$z; will display aa

That's all I can think of right now. I may add some more later.

share|improve this answer

Don't use qw. This is waste of two characters that could be used in better way. For example, don't write the following.

@i=qw(unique value);

Instead use barewords.


Or if you cannot use barewords, use glob syntax.

@i=<unique value>;

glob syntax can also be used for interesting effects.

share|improve this answer

Don't use strict. (don't quote me on this, PCG.SE context kinda matters) And, more importantly, don't code as if under strict. The usual suspects:

  • don't my-declare variables if you can avoid it. The only variables that really need my are those you want lexically scoped. That's barely any of them when golfing, where you don't need scope protection and tend to fully control recursion.
  • don't quote one-word strings: (example). Do ensure you don't have a function with the same name, though.
share|improve this answer
print hello won't work. It actually means print hello $_ (print $_ to filehandle hello). –  xfix Oct 22 '12 at 12:25
@GlitchMr thanks! (and now I'm bummed, because my point is still valid, just not with print, and now I can't find a nice and short example) –  J B Oct 22 '12 at 18:10
@JB here's a good example: codegolf.stackexchange.com/a/8746/3348 –  ardnew Oct 22 '12 at 19:45
@ardnew: thanks! –  J B Oct 25 '12 at 21:02

-n and unmatched curly brackets

It is well known that the command line switch -n can be used to execute the script once for every line.

perl --help says:

  -n                assume "while (<>) { ... }" loop around program

What it doesn't say explicitly is that Perl doesn't just assume a loop around the program; it literally wraps while (<>) { ... } around it.

This way, the following commands are equivalent to each other:

 perl -e 'while(<>){code}morecode'
 perl -ne 'code;END{morecode}'
 perl -ne 'code}{morecode'
share|improve this answer

redo adds loop behavior to a block without for or while. {redo} is an infinite loop.

share|improve this answer

Don't parenthesize function calls.

Perl lets you call a known (core or predeclared) function using the NAME LIST syntax. This lets you drop the & sigil (if you were still using it) as well as the parentheses.

For example: $v=join'',<>

Full documentation

share|improve this answer

Try to use the value of an assignment expression, like so:

# 14 characters

# 13 characters, saves 1

This works because $n is 2 characters in Perl. You may change $n to () at no cost, and save 1 semicolon by moving the assignment into the parentheses.

share|improve this answer

You can run multiple different statements within nested ternary logic.

Suppose you have a big if-elsif statement. This could be any logic and any number of statements.

if( $_ < 1 ) {
    say $a.$b.$c;
} elsif($_ < 2 ) {
    say $a.$b.$c;
} elsif( $_ < 3) {
    say $a.$b.$c;

You can use (cmd1, cmd2, cmd3) inside the ternary operator to run all of the commands.

$_ < 1 ?
$_ < 2 ?
$_ < 3 ?
0; #put the else here if we have one

Here's a dummy example:

perl -nE'$_<1?($a=1,$b=2,$c=3,say$a.$b.$c):$_<2?($a=3,$b=2,$c=1,say$a.$b.$c):$_<3?($a=2,$b=2,$c=2,say$a.$b.$c):0;' <(echo 2)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.