Wiki: Perl

Perl 4 Package Separator

Instead of

utf8::decode $foo

Use

utf8'decode $foo

Chained comparison evaluation

In Perl v5.32+, comparisons chain such that something like $a < $b < $c evaluates as $a < $b && $b < $c. This means you can often shorten a conditional call to say:

$_>1&&say
$_>1>say

Variable reset

Several variables can be reset via various means:

$.=5;<>;say$.    # 0 if there is nothing on STDIN
$@=5;eval;say$@  # ''
$!=5;-A;say 0+$! # 2

Glob assignment

In modern Perls you can't assign to a numeric variable greater than 0:

${0}=1;say$0 # OK
${1}=1;say$1 # Not OK (Modification of a read-only value)

But you can use a glob to bypass this:

*{1}=\1;say$1 # OK

Thelen's device

\ forces autovivication:

$a{5}++;say 0+%a # 1
\$b{5};say 0+%b  # 1

You can use this, for example, to count unique values in a set:

\%a{1,1,2,4,2,4,4,2};say 0+%a # 3

Using $0

Sometimes $0 can be used as a useful store for when some condition is true or false.

Consider this solution to Sum of Divisors for OCaml Golf Competition:

#!perl -p
$'%$_ or$s+=$_ for//..($s=$_)/2;s/$/: $s/

This can be golfed a byte by storing the sum in $0:

#!perl -p
map${$'%-$_}+=$_,//..($0=$_)/2;s/$/: $0/