One-liners
perl -e '<code>'
Run code given on the command line
perl -E '<code>'
Same, with say and modern features on
perl -ne '<code>'
Run code once per input line
perl -pe '<code>'
Per line, then print $_
perl -i[.bak] -pe '<code>' <file>
Edit files in place
Without a suffix no backup is kept. Test without -i first.
perl -l
Chomp input lines, add \n to print
perl -a -F<sep>
Split each line into @F
perl -0777 -ne '<code>'
Slurp whole file as one string
perl -M<Module> -e '<code>'
Load a module first
perl -c <script.pl>
Check syntax without running
perl -pe 'BEGIN{...} END{...}'
Run setup or summary around the loop
perl -Mutf8 -CS -e '<code>'
Treat source and I/O as UTF-8
$.
Current input line number
$0 / @ARGV / %ENV
Script name, arguments, environment
Variables and data
my $x = <value>;
Declare a lexical scalar
my @a = (<1>, <2>, <3>);
Declare an array
my %h = (<k> => <v>);
Declare a hash
$a[0] / $a[-1]
First / last element
scalar @a / $#a
Element count / last index
push @a, <x> / pop @a
Add / remove at the end
unshift @a, <x> / shift @a
Add / remove at the start
@a[<1>,<2>] / @h{<k1>,<k2>}
Array / hash slice
keys %h / values %h
All keys / all values
exists $h{<k>} / delete $h{<k>}
Test for / remove a key
sort { $a <=> $b } @a
Numeric sort
sort { $a cmp $b } @a
String sort
map { <expr> } @a
Transform each element
grep { <cond> } @a
Keep matching elements
join(<sep>, @a) / split(/<re>/, $s)
Join / split
\@a / \%h / sub {...}
Reference to array / hash / code
$r->[0] / $r->{<k>} / @$r
Dereference
{ <k> => [1,2] }
Anonymous nested structure
defined $x
True if not undef
Strings and operators
"Hi $name @{[ f() ]}"
Interpolate variables and expressions
$a . $b / $s x <n>
Concatenate / repeat
== != < > <=>
Numeric compare
eq ne lt gt cmp
String compare
&& || // !
Logical and, or, defined-or, not
$x //= <default>
Set only if undef
length $s / uc $s / lc $s
Length, upper, lower
substr($s, <off>, <len>)
Extract or replace a substring
index($s, <t>) / rindex($s, <t>)
Find substring position
sprintf("%-10s %5.2f", ...)
Format values
chomp $s / chop $s
Strip newline / last char
q() / qq() / qw(a b c)
Quote, double-quote, word list
tr/a-z/A-Z/
Transliterate characters
.. (1..10, 'a'..'e')
Range
Regex
$s =~ /<re>/
Test for a match
$s =~ s/<re>/<new>/g
Substitute all
$s =~ s/<re>/<expr>/e
Replacement is Perl code
$s !~ /<re>/
Test for no match
($a,$b) = $s =~ /(\d+)-(\d+)/
Capture into variables
$1 $2 $&
Capture groups, whole match
/(?<name>\w+)/ then $+{name}
Named capture
my @all = $s =~ /<re>/g
All matches in list context
/i /x /m /s
Ignore case, extended, multiline, dot-all
s/<re>/<new>/r
Return the result, keep original
\d \w \s \b
Digit, word, space, boundary
*? +? ??
Non-greedy quantifiers
qr/<re>/
Compile a reusable regex
split /\s+/, $s
Split on a pattern
\Q$var\E
Quote metacharacters in interpolation
Control flow and subs
if (<c>) {...} elsif (<c>) {...} else
{...}
Conditional
<stmt> if <c>; / <stmt> unless
<c>;
Postfix conditional
for my $x (@a) {...}
Loop over a list
for (my $i=0; $i<<n>; $i++) {...}
C-style loop
while (<c>) {...}
Loop on a condition
next / last / redo
Skip / exit / repeat iteration
sub <name> { my ($a,$b) = @_; return ...; }
Define a sub
shift
Take the first sub argument
use feature 'signatures'; sub f($x,$y=1){}
Sub signatures
die "<msg>\n" / warn
"<msg>"
Raise error / warn
eval { ... }; if ($@) {...}
Catch exceptions
Files and I/O
open(my $fh, '<', $f) or die "$!";
Open for reading
open(my $fh, '>', $f) / '>>'
Open for write / append
while (my $l = <$fh>) {...}
Read line by line
my @lines = <$fh>;
Read all lines
print $fh "text\n";
Write to a handle
close $fh;
Close a handle
local $/; my $c = <$fh>;
Slurp a whole file
-e -f -d -r -s $path
File tests: exists, file, dir, readable, size
opendir / readdir / glob('*.txt')
List directory entries
unlink / rename / mkdir / rmdir
File operations
my $out = `cmd`;
Capture command output
system('cmd', @args) == 0 or die
Run a command safely
<STDIN> / STDERR
Standard input / error handle
binmode(STDOUT, ':utf8')
Set encoding layer