Contents

Perl Cheat Sheet

Modern Perl from the first script to classes, with scalars, arrays, hashes, references, regular expressions, files and the one-liners Perl is famous for. Every example with output ran on Perl 5.42.2 and the output under it is what it printed; rows for newer features name the Perl version that added them.

By Bogdan SanduUpdated December 2, 2026Tested on Perl 5.42.2

Perl one-liner builder

Pick a task and fill in the blanks to get a ready perl command for your shell. Nothing is sent anywhere.

Command

    

Perl regex explainer

Paste a Perl pattern, with or without the slashes and flags, and read what each piece matches.

Covers anchors, character classes, escapes, quantifiers, lazy and possessive forms, groups, named captures, lookarounds, backreferences, alternation and the trailing flags.

Explanation

Install & Run

Run Perl

Check the version and run a one-line program

-E is like -e but turns on every feature of your Perl version, including say. Most Linux distributions and macOS ship Perl; on Windows use Strawberry Perl.

$ perl -v
$ perl -e 'print "Hello, world\n"'
$ perl -E 'say "Hello, world"'

A script with a shebang line

use v5.40 enables strict, warnings, say, signatures and try/catch in one line, and fails early on an older Perl. shift outside a sub takes the first command line argument from @ARGV.

hello.pl
#!/usr/bin/env perl
use v5.40;

my $name = shift // 'world';
say "Hello, $name";Hello, world

Run it

$ perl hello.pl Ann
$ chmod +x hello.pl && ./hello.pl Ann

The safety lines

What use v5.36 and later turn on

Without strict, a typo in a variable name silently creates a new global. Always start with one of these lines.

LineEnables
use v5.36;strict, warnings, say, signatures, isa; disables indirect object syntax
use v5.40;Everything in 5.36, plus try/catch and stable builtin functions such as true, false and trim
use v5.44;The current version bundle
use strict; use warnings;The classic pair for code that must run on old Perls

Read the documentation from the terminal

-f looks up a built-in function, -v a special variable, and -q searches the FAQ.

$ perldoc perlintro
$ perldoc -f split
$ perldoc -v '$_'
$ perldoc -q "sort a hash"
$ perldoc List::Util

Variables & Sigils

Three kinds of variables

Scalars, arrays and hashes

The sigil shows what you get back, not what the variable is: $langs[0] is one scalar from the array @langs, $age{ann} one scalar from the hash %age.

use v5.40;

my $name  = 'Ann';
my @langs = ('Perl', 'Go', 'Rust');
my %age   = (ann => 31, bob => 27);

say $name;
say $langs[0];
say $age{ann};
say scalar @langs;Ann
Perl
31
3

Interpolation in double quotes

Double quotes interpolate scalars and arrays, with array elements joined by a space. Escape a literal @ in double quotes, or Perl tries to interpolate an array.

use v5.40;

my @langs = ('Perl', 'Go');
my %h = (k => 'v');
say "langs: @langs";
say "first: $langs[0], key: $h{k}";
say 'single quotes: $langs[0]';
say "email\@example.com";langs: Perl Go
first: Perl, key: v
single quotes: $langs[0]
email@example.com

undef and defined

// is defined-or: it returns the right side only when the left is undef, unlike ||, which also replaces 0 and the empty string.

use v5.40;

my $x;
say defined $x ? 'defined' : 'undef';
my $port = $ENV{NO_SUCH_VAR} // 8080;
say $port;undef
8080

Comments and POD

# a line comment

=pod

Block documentation, also used as a multi-line comment.

=cut

print "after the pod block\n";after the pod block

Strings

String operators

Join, repeat and compare

Strings compare with eq, ne, lt, gt, le, ge and cmp; numbers with ==, !=, <, >, <=, >= and <=>. Mixing them up is the most common Perl bug.

use v5.40;

my $s = 'Perl' . ' ' . 'rocks';
say $s;
say '-' x 10;
say length $s;
say 'abc' lt 'abd' ? 'lt' : 'ge';
say 'apple' cmp 'banana';Perl rocks
----------
10
lt
-1

Substrings, search and case

use v5.40;

my $s = 'Hello, World';
say substr($s, 0, 5);
say substr($s, -5);
say index($s, 'World');
say uc $s;
say lc $s;
say ucfirst lc 'pERL';
substr($s, 0, 5) = 'Howdy';
say $s;Hello
World
7
HELLO, WORLD
hello, world
Perl
Howdy, World

Trim, chomp and reverse

Perl 5.40+

chomp removes a trailing newline and nothing else. trim is a builtin function that use v5.40 imports; on older Perls use s/^\s+|\s+$//g.

use v5.40;

my $line = "  padded text  \n";
chomp $line;
say "[" . trim($line) . "]";
say scalar reverse 'stressed';[padded text]
desserts

Formatting

sprintf and printf

use v5.40;

printf "%-8s|%5.2f|%04d|%x|%e\n", 'name', 3.14159, 42, 255, 12345.678;
my $s = sprintf '%s has %d items', 'cart', 3;
say $s;
say sprintf '%3d%%', 75;name    | 3.14|0042|ff|1.234568e+04
cart has 3 items
 75%

Heredocs

The ~ in <<~ removes the indentation of the closing line from every line, so a heredoc can be indented with the code. A quoted marker like 'RAW' turns off interpolation.

use v5.40;

my $user = 'ann';
print <<~EOT;
    Dear $user,
      thanks for signing up.
    EOT
print <<~'RAW';
    No $interpolation here
    RAWDear ann,
  thanks for signing up.
No $interpolation here

Numbers & Math

Arithmetic

Operators and division

Division always returns a floating point result, so use int() to truncate. With a positive right side, % returns a result with the sign of the right side, so -7 % 3 is 2.

use v5.40;

say 7 / 2;
say int(7 / 2);
say 7 % 3;
say -7 % 3;
say 2 ** 10;
say 10 / 3;3.5
3
1
2
1024
3.33333333333333

Rounding

sprintf rounds the binary value, so 2.675 prints 2.67, and halves go to the even neighbour. Perl has no round function; use sprintf, or Math::BigFloat when cents matter.

use v5.40;
use POSIX qw(floor ceil);

say sprintf('%.2f', 2.675);
say sprintf('%.0f', 2.5);
say sprintf('%.0f', 3.5);
say floor(-2.5), ' ', ceil(-2.5);2.67
2
4
-3 -2

Numbers in other bases and with separators

use v5.40;

say 1_000_000 + 1;
say hex 'ff';
say oct '0755';
say oct '0b1010';
say sprintf '%b', 10;
say sprintf '%o', 493;1000001
255
493
10
1010
755

Random numbers

rand is not cryptographically secure. For tokens and passwords use Crypt::URandom or read from /dev/urandom.

use v5.40;

my $dice = 1 + int rand 6;
my @items = ('a' .. 'e');
my $pick = $items[rand @items];
say "dice is 1 to 6: ", ($dice >= 1 && $dice <= 6 ? 'yes' : 'no');dice is 1 to 6: yes

Arrays & Lists

Build and change arrays

Add and remove elements

use v5.40;

my @a = (1, 2, 3);
push @a, 4, 5;
unshift @a, 0;
my $last  = pop @a;
my $first = shift @a;
say "@a | removed $first and $last";1 2 3 4 | removed 0 and 5

Length, last index and slices

scalar @a is the number of elements and $#a the last index. @a[1..3] is a slice: several elements at once, so it uses the @ sigil.

use v5.40;

my @a = ('a' .. 'f');
say scalar @a;
say $#a;
say $a[-1];
say "@a[1..3]";
say "@a[0, -1]";6
5
f
b c d
a f

splice: remove, insert or replace in the middle

use v5.40;

my @a = (1 .. 6);
my @gone = splice @a, 1, 2;
say "@a | removed @gone";
splice @a, 1, 0, 'x', 'y';
say "@a";1 4 5 6 | removed 2 3
1 x y 4 5 6

Transform lists

split, join, map and grep

Inside map and grep, $_ is each element in turn. Functions such as uc and length use $_ when called with no argument.

use v5.40;

my @parts = split /,\s*/, 'perl, go,rust';
say join '|', @parts;
my @upper = map { uc } @parts;
say "@upper";
my @long = grep { length > 2 } @parts;
say "@long";perl|go|rust
PERL GO RUST
perl rust

Search a list with List::Util

List::Util ships with Perl. Perl 5.42 also has experimental any and all keywords that work without the module.

use v5.40;
use List::Util qw(first sum max min uniq shuffle any);

my @n = (3, 9, 4, 9, 1);
say first { $_ > 3 } @n;
say sum @n;
say max(@n), ' ', min(@n);
say join ',', uniq @n;
say( (any { $_ == 4 } @n) ? 'has 4' : 'no 4' );9
26
9 1
3,9,4,1
has 4

Loop with the index

Perl 5.40+

Iterating over several values at a time became stable in Perl 5.40, together with builtin::indexed. On older Perls use for my $i (0 .. $#langs).

use v5.40;

my @langs = ('Perl', 'Go', 'Rust');
for my ($i, $lang) (builtin::indexed @langs) {
    say "$i: $lang";
}0: Perl
1: Go
2: Rust

Hashes

Use hashes

Create, read, test and delete

exists checks whether a key is there; the value can still be 0 or undef. Hash order is random, so sort the keys whenever output order matters.

use v5.40;

my %stock = (apple => 3, pear => 0);
$stock{plum} = 7;
say exists $stock{pear} ? 'pear known' : 'no pear';
say $stock{pear} ? 'pear in stock' : 'pear sold out';
delete $stock{apple};
say join ', ', sort keys %stock;
say scalar keys %stock;pear known
pear sold out
pear, plum
2

Loop over keys and values

Perl 5.40+

use v5.40;

my %age = (ann => 31, bob => 27, cy => 35);
for my $name (sort keys %age) {
    say "$name is $age{$name}";
}
for my ($k, $v) (map { $_, $age{$_} } sort keys %age) {
    say "$k=$v";
}ann is 31
bob is 27
cy is 35
ann=31
bob=27
cy=35

Sort by value

use v5.40;

my %score = (ann => 72, bob => 95, cy => 88);
for my $name (sort { $score{$b} <=> $score{$a} } keys %score) {
    say "$name $score{$name}";
}bob 95
cy 88
ann 72

Slices, invert and count

@h{...} returns values, %h{...} returns key and value pairs. $count{$_}++ is the standard way to count things in Perl.

use v5.40;

my %h = (a => 1, b => 2, c => 3);
my @two = @h{qw(a c)};
say "@two";
my %pairs = %h{qw(a b)};
say join ',', map { "$_=$pairs{$_}" } sort keys %pairs;
my %by_value = reverse %h;
say $by_value{2};
my %count;
$count{$_}++ for qw(x y x z x);
say join ' ', map { "$_:$count{$_}" } sort keys %count;1 3
a=1,b=2
b
x:3 y:1 z:1

References & Nested Data

References

Make references and follow them

[...] builds an anonymous array and {...} an anonymous hash, each returning a reference. The arrow is optional between subscripts, so $hr->{tags}[1] is short for $hr->{tags}->[1].

use v5.40;

my @a = (1, 2, 3);
my $ar = \@a;
my $hr = { name => 'Ann', tags => ['admin', 'dev'] };
say $ar->[0];
say scalar @$ar;
say $hr->{name};
say $hr->{tags}[1];
say ref $ar, ' ', ref $hr;1
3
Ann
dev
ARRAY HASH

Postfix dereference

->@* and ->%* read left to right and are easier to scan than @{ $data->{users} }. They are on by default since Perl 5.24.

use v5.40;

my $data = { users => ['ann', 'bob'], roles => { ann => 'admin' } };
say join ',', $data->{users}->@*;
say scalar $data->{users}->@*;
say join ',', sort keys $data->{roles}->%*;
say $data->{users}->$#*;ann,bob
2
ann
1

Build a list of records

use v5.40;

my @people = (
    { name => 'Ann', age => 31 },
    { name => 'Bob', age => 27 },
);
push @people, { name => 'Cy', age => 35 };
for my $p (sort { $a->{age} <=> $b->{age} } @people) {
    say "$p->{name} ($p->{age})";
}
my %by_name = map { $_->{name} => $_ } @people;
say $by_name{Cy}{age};Bob (27)
Ann (31)
Cy (35)
35

Print any structure with Data::Dumper

Sortkeys makes the output stable from run to run, which matters in tests and logs.

use v5.40;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;

print Dumper({ id => 7, tags => ['a', 'b'] });$VAR1 = {
  'id' => 7,
  'tags' => [
    'a',
    'b'
  ]
};

Copy deep structures

Copying the top-level hash still shares the inner array. dclone from the core Storable module copies every level.

use v5.40;
use Storable qw(dclone);

my $orig = { list => [1, 2] };
my $shallow = { %$orig };
my $deep = dclone($orig);
push $orig->{list}->@*, 3;
say scalar $shallow->{list}->@*;
say scalar $deep->{list}->@*;3
2

Control Flow

Conditions

if, elsif, else and unless

Perl writes elsif, not elseif or else if. Braces are always required, even around one statement.

use v5.40;

my $n = 15;
if    ($n % 15 == 0) { say 'FizzBuzz' }
elsif ($n % 3 == 0)  { say 'Fizz' }
else                 { say $n }
unless ($n > 100) { say 'small' }FizzBuzz
small

Statement modifiers and the ternary

An array in boolean context is true when it has elements.

use v5.40;

my @queue = (1, 2);
say 'queue has items' if @queue;
say 'never printed' unless @queue;
my $label = @queue > 1 ? 'many' : 'one';
say $label;queue has items
many

What counts as false

ValueBoolean
0, '0', '', undefFalse
'0.0', '00', ' ', '0E0'True, because they are not exactly '0'
Empty array or hashFalse
Any referenceTrue

Loops

for, foreach and while

for and foreach are the same keyword. The C-style loop works but for my $i (1 .. 3) is the usual form.

use v5.40;

for my $i (1 .. 3) { print "$i " }
print "\n";
for (my $i = 0; $i < 6; $i += 2) { print "$i " }
print "\n";
my $n = 3;
while ($n > 0) { print $n--, ' ' }
print "\n";1 2 3 
0 2 4 
3 2 1 

last, next and labels

last is break and next is continue in other languages. A label lets either one leave an outer loop.

use v5.40;

OUTER:
for my $row (1 .. 3) {
    for my $col (1 .. 3) {
        next OUTER if $col > $row;
        last OUTER if $row == 3;
        print "$row$col ";
    }
}
print "\n";11 21 22 

any and all as keywords

Perl 5.42+

These keywords stop at the first element that decides the answer, like List::Util's functions, but run as core operators. They are experimental in Perl 5.42 and 5.44.

use v5.42;
use feature qw(keyword_any keyword_all);
no warnings qw(experimental::keyword_any experimental::keyword_all);

my @n = (2, 4, 6);
say 'all even' if all { $_ % 2 == 0 } @n;
say 'has a 4'  if any { $_ == 4 } @n;all even
has a 4

Subroutines & Signatures

Define and call subs

Signatures

Perl 5.36+

Signatures are stable since Perl 5.36 and on with use v5.36 or later. They check the number of arguments, so calling greet() with none dies with a clear error.

use v5.40;

sub greet ($name, $greeting = 'Hello') {
    return "$greeting, $name";
}
say greet('Ann');
say greet('Bob', 'Hi');Hello, Ann
Hi, Bob

Defaults that apply when the argument is undef or false

Perl 5.38+

use v5.40;

sub port ($p //= 8080) { $p }
sub name ($n ||= 'guest') { $n }
say port(undef);
say name('');8080
guest

Slurpy parameters

use v5.40;

sub total ($label, @nums) {
    my $sum = 0;
    $sum += $_ for @nums;
    return "$label: $sum";
}
sub opts (%o) { join ',', map { "$_=$o{$_}" } sort keys %o }
say total('sum', 1, 2, 3);
say opts(b => 2, a => 1);sum: 6
a=1,b=2

Named parameters

Perl 5.44+

New and experimental in Perl 5.44: parameters written :$name come after the positional ones and are passed as name and value pairs, in any order. One without a default is mandatory, so leaving it out raises an exception.

use v5.44;
no warnings 'experimental::signature_named_parameters';

sub connect_db ($host, :$port = 5432, :$user = 'app') {
    return "$user\@$host:$port";
}
say connect_db('db1');
say connect_db('db1', user => 'admin', port => 6432);

The classic way with @_

Before signatures, arguments arrived in @_ and you copied them out. You will see this in most existing code.

use strict;
use warnings;

sub add {
    my ($x, $y) = @_;
    return $x + $y;
}
print add(2, 3), "\n";5

Return values and context

Return a list, or a different value in scalar context

use v5.40;

sub minmax (@n) {
    my @s = sort { $a <=> $b } @n;
    return ($s[0], $s[-1]);
}
my ($lo, $hi) = minmax(5, 1, 9);
say "$lo $hi";

sub ctx { wantarray ? 'list' : 'scalar' }
my @l = ctx();
my $s = ctx();
say "$l[0] $s";1 9
list scalar

Anonymous subs and closures

A closure keeps the lexical variables it was created with. A hash of code references is the usual dispatch table.

use v5.40;

sub make_counter ($start) {
    my $n = $start;
    return sub { return $n++ };
}
my $c = make_counter(10);
$c->() for 1 .. 2;
say $c->();
my %dispatch = (add => sub ($x, $y) { $x + $y }, mul => sub ($x, $y) { $x * $y });
say $dispatch{mul}->(6, 7);12
42

Regular Expressions

Match

Test and capture

In list context a match returns its captures, so my ($x) = $s =~ /(...)/ copies the first group in one line. The parentheses around $secs matter.

use v5.40;

my $log = '2026-12-02 ERROR db timeout after 30s';
if ($log =~ /^(\d{4})-(\d\d)-(\d\d) (\w+)/) {
    say "year $1, level $4";
}
my ($secs) = $log =~ /(\d+)s$/;
say $secs;
say 'no warning' if $log !~ /WARN/;year 2026, level ERROR
30
no warning

Named captures

use v5.40;

if ('ann@example.com' =~ /(?<user>[^@]+)@(?<domain>.+)/) {
    say "$+{user} at $+{domain}";
}ann at example.com

All matches with /g

() = forces list context and the assignment then returns the number of matches.

use v5.40;

my $text = 'ids: 12, 7, 409';
my @ids = $text =~ /(\d+)/g;
say "@ids";
my $count = () = $text =~ /\d+/g;
say $count;
while ($text =~ /(\d+)/g) {
    say "found $1 ending at ", pos $text;
}12 7 409
3
found 12 ending at 7
found 7 ending at 10
found 409 ending at 15

Replace

Substitute in place, or return a copy with /r

/r returns the changed string and leaves the original alone, which lets a substitution sit inside an expression.

use v5.40;

my $s = 'colour colour';
(my $copy = $s) =~ s/colour/color/;
say $copy;
$s =~ s/colour/color/g;
say $s;
my $slug = lc('Hello World Again') =~ s/\s+/-/gr;
say $slug;color colour
color color
hello-world-again

Compute the replacement with /e

use v5.40;

my $prices = 'apple 1.50, pear 2.25';
$prices =~ s/(\d+\.\d+)/sprintf '%.2f', $1 * 1.2/ge;
say $prices;apple 1.80, pear 2.70

Translate characters with tr

tr counts the characters it matches, so an empty replacement list counts without changing anything.

use v5.40;

my $dna = 'ATGCCA';
(my $comp = $dna) =~ tr/ATGC/TACG/;
say $comp;
my $vowels = ($dna =~ tr/AEIOU//);
say $vowels;
say 'Hello' =~ tr/a-z/A-Z/r;TACGGT
2
HELLO

Modifiers and building blocks

Common modifiers

ModifierEffect
iCase-insensitive
gEvery match, not just the first
m^ and $ match at each line
s. also matches a newline
xIgnore spaces and allow # comments in the pattern
rReturn the result of s/// or tr/// instead of changing the string
eTreat the replacement as code
nPlain parentheses do not capture

Readable patterns with /x and qr

use v5.40;

my $date = qr{
    (?<y> \d{4} ) -   # year
    (?<m> \d{2} ) -   # month
    (?<d> \d{2} )     # day
}x;
say "$+{d}.$+{m}.$+{y}" if '2026-12-02' =~ $date;
my @found = grep { /^$date$/ } ('2026-01-31', 'not a date');
say scalar @found;02.12.2026
1

Greedy, lazy and lookarounds

use v5.40;

my $html = '<b>one</b> <b>two</b>';
my ($greedy) = $html =~ /<b>(.*)<\/b>/;
my ($lazy)   = $html =~ /<b>(.*?)<\/b>/;
say $greedy;
say $lazy;
(my $n = '1234567') =~ s/(?<=\d)(?=(?:\d{3})+$)/,/g;
say $n;one</b> <b>two
one
1,234,567

Split with a pattern

split drops trailing empty fields unless you pass a negative limit, which matters when reading CSV-like lines. Capturing parentheses keep the separators.

use v5.40;

say join '|', split /\s*;\s*/, 'a ; b;c';
say join '|', split //, 'abc';
say join '|', split /(-)/, 'a-b';
say scalar(my @f = split /,/, 'a,b,,,');
say scalar(my @g = split /,/, 'a,b,,,', -1);a|b|c
a|b|c
a|-|b
2
5

Files & Directories

Read and write files

Write, append and read line by line

Always use the three-argument form of open with a lexical filehandle, and check the result: $! holds the reason it failed. $. is the current line number.

use v5.40;

open my $out, '>', 'notes.txt' or die "Cannot write notes.txt: $!";
print $out "first\nsecond\n";
close $out;

open my $app, '>>', 'notes.txt' or die $!;
say $app 'third';
close $app;

open my $in, '<', 'notes.txt' or die $!;
while (my $line = <$in>) {
    chomp $line;
    say "$.: $line";
}
close $in;1: first
2: second
3: third

Read a whole file at once

Setting $/, the input record separator, to undef makes <$fh> return the whole file. Reading in list context returns all the lines.

use v5.40;

open my $w, '>', 'config.ini' or die $!;
print $w "a=1\nb=2\n";
close $w;

my $text = do { local $/; open my $fh, '<', 'config.ini' or die $!; <$fh> };
say length $text;
open my $fh, '<', 'config.ini' or die $!;
my @lines = <$fh>;
say scalar @lines;8
2

Text with UTF-8

use utf8 says the source file is UTF-8. The encoding layers on open and binmode decode input and encode output, so length counts characters, not bytes.

use v5.40;
use utf8;
binmode STDOUT, ':encoding(UTF-8)';

open my $w, '>:encoding(UTF-8)', 'names.txt' or die $!;
say $w 'Zoë';
close $w;
open my $r, '<:encoding(UTF-8)', 'names.txt' or die $!;
my $name = <$r>;
chomp $name;
say "$name has ", length($name), ' characters';Zoë has 3 characters

Files and directories

File tests

use v5.40;

open my $w, '>', 'data.csv' or die $!;
print $w "x\n";
close $w;
say -e 'data.csv' ? 'exists' : 'missing';
say -f 'data.csv' ? 'regular file' : 'not a file';
say -d '.' ? 'directory' : 'not a directory';
say -s 'data.csv';
say -e 'nope.txt' ? 'exists' : 'missing';exists
regular file
directory
2
missing

File test operators

TestTrue when
-eIt exists
-f and -dIt is a plain file or a directory
-sIt is not empty; returns the size in bytes
-r -w -xReadable, writable, executable by you
-lIt is a symbolic link
-MReturns the age in days since the last change

List, create and remove

use v5.40;
use File::Path qw(make_path remove_tree);

make_path('out/logs');
for my $n (1 .. 3) { open my $f, '>', "out/logs/$n.log" or die $!; close $f }
my @logs = sort glob 'out/logs/*.log';
say "@logs";
opendir my $dh, 'out/logs' or die $!;
my @names = sort grep { !/^\./ } readdir $dh;
closedir $dh;
say "@names";
rename 'out/logs/1.log', 'out/logs/one.log' or die $!;
unlink 'out/logs/2.log';
remove_tree('out');
say -d 'out' ? 'still there' : 'removed';out/logs/1.log out/logs/2.log out/logs/3.log
1.log 2.log 3.log
removed

One-Liners

Perl started as a better sed and awk, and its command line switches still make it one of the fastest ways to edit and filter text.

Switches

The switches that make one-liners work

SwitchDoes
-e 'code'Run code from the command line
-E 'code'Same, with every feature, so say works
-nLoop over input lines without printing
-pLoop over input lines and print each one
-lChomp input lines and add a newline to print
-aSplit each line into @F on whitespace
-F,Split on a comma instead; implies -a and -n
-i.bakEdit files in place, keeping a .bak copy
-0777Read the whole file as one string
-M ModuleLoad a module

Recipes

Filter lines like grep

$ printf 'ok 1\nERROR 2\nok 3\nERROR 4\n' > app.log
$ perl -ne 'print if /ERROR/' app.log
$ perl -ne 'print unless /^ok/' app.log
$ perl -ne 'print "$.: $_" if /ERROR/' app.logERROR 2
ERROR 4
ERROR 2
ERROR 4
2: ERROR 2
4: ERROR 4

Replace text like sed, in place

-i.bak keeps the original as app.conf.bak. Use -i alone to skip the backup once you trust the command.

$ printf 'host=localhost\nport=80\n' > app.conf
$ perl -i.bak -pe 's/localhost/db.internal/' app.conf
$ cat app.conf
$ ls app.conf*host=db.internal
port=80
app.conf
app.conf.bak

Work with columns like awk

$ printf 'ann 31 dev\nbob 27 ops\ncy 35 dev\n' > people.txt
$ perl -lane 'print $F[0]' people.txt
$ perl -lane '$sum += $F[1]; END { print $sum }' people.txt
$ perl -lane 'print "$F[0]" if $F[2] eq "dev"' people.txt
$ printf 'a,1\nb,2\n' | perl -F, -lane 'print $F[1]'ann
bob
cy
93
ann
cy
1
2

Count, dedupe and number lines

$ printf 'b\na\nb\nc\na\n' > words.txt
$ perl -ne '$seen{$_}++ or print' words.txt
$ perl -lne '$c{$_}++; END { print "$_ $c{$_}" for sort keys %c }' words.txt
$ perl -ne 'END { print "$.\n" }' words.txtb
a
c
a 2
b 2
c 1
5

Whole-file and multi-line edits

With -0777 the whole file is one string, so a pattern can span lines. This one squeezes runs of blank lines down to one.

$ printf 'one\n\n\n\ntwo\n' > gaps.txt
$ perl -0777 -pe 's/\n{3,}/\n\n/g' gaps.txtone

two

Errors & Exceptions

Throw and catch

try and catch

Perl 5.40+

try and catch are stable since Perl 5.40; finally is still experimental and warns unless you add no warnings 'experimental::try'. A message without a trailing newline gets " at FILE line N." appended.

use v5.40;
no warnings 'experimental::try';

sub parse_age ($s) {
    die "not a number: $s\n" unless $s =~ /^\d+$/;
    return $s + 0;
}
try {
    say parse_age('42');
    say parse_age('forty');
}
catch ($e) {
    chomp $e;
    say "error: $e";
}
finally {
    say 'done';
}42
error: not a number: forty
done

The classic eval block

Check the return value of eval, not just $@: ending the block with 1 makes success unambiguous. die can throw any value, including a hash reference or an object.

use strict;
use warnings;

my $ok = eval {
    die { code => 404, msg => 'missing' };
    1;
};
unless ($ok) {
    my $err = $@;
    print "code $err->{code}: $err->{msg}\n";
}code 404: missing

Warnings and system errors

$! holds the operating system error after a failed system call. The second warning comes from use warnings, which catches a string being used as a number.

use v5.40;

open my $fh, '<', '/no/such/file' or warn "open failed: $!\n";
say 'still running';
my $n = '3 apples' + 2;
say $n;still running
5
open failed: No such file or directory
Argument "3 apples" isn't numeric in addition (+) at script.pl line 5.

Report errors from the caller's point of view

croak reports the line where the sub was called, not where it died, which is what users of a module need.

use v5.40;
use Carp qw(croak carp);

sub withdraw ($amount) {
    croak 'amount must be positive' if $amount <= 0;
    return $amount;
}
eval { withdraw(-5) };
print $@ =~ s/ at .*//sr, "\n";amount must be positive

Packages & Classic OOP

bless-based classes

A class with a constructor and methods

bless ties a reference to a package, and method calls look up subs in that package. This is how almost every CPAN module and older codebase builds objects.

use v5.40;

package Counter {
    sub new ($class, %args) {
        my $self = { count => $args{start} // 0 };
        return bless $self, $class;
    }
    sub inc ($self, $by = 1) { $self->{count} += $by; return $self }
    sub count ($self) { $self->{count} }
}

my $c = Counter->new(start => 5);
$c->inc->inc(3);
say $c->count;
say ref $c;9
Counter

Inheritance

use parent sets @ISA. -norequire is only needed here because both packages live in one file.

use v5.40;

package Animal {
    sub new ($class, $name) { bless { name => $name }, $class }
    sub speak ($self) { sprintf '%s says %s', $self->{name}, $self->sound }
    sub sound ($self) { '...' }
}
package Dog {
    use parent -norequire, 'Animal';
    sub sound ($self) { 'woof' }
}

my $d = Dog->new('Rex');
say $d->speak;
say $d->isa('Animal') ? 'is an Animal' : 'not an Animal';
say Dog->can('speak') ? 'can speak' : 'cannot speak';Rex says woof
is an Animal
can speak

The isa operator

Perl 5.36+

isa never dies on a non-object, unlike calling ->isa on a plain string or undef.

use v5.40;

package Shape { sub new ($c) { bless {}, $c } }
my $s = Shape->new;
say $s isa Shape ? 'yes' : 'no';
say 'text' isa Shape ? 'yes' : 'no';yes
no

Modern class Syntax

class, field and method

Experimental since Perl 5.38

A class with fields and accessors

Perl 5.42+

:param fills the field from the constructor, :reader (5.40) adds a getter and :writer (5.42) a setter named set_x. Inside a method, $self and the fields are already in scope.

use v5.42;
use experimental 'class';

class Point {
    field $x :param :reader :writer = 0;
    field $y :param :reader = 0;
    method to_string { "($x, $y)" }
    method move ($dx, $dy) { $x += $dx; $y += $dy; return $self }
}

my $p = Point->new(x => 3);
$p->move(1, 2);
say $p->to_string;
$p->set_x(10);
say $p->x;(4, 2)
10

Run code after construction with ADJUST

Perl 5.38+

use v5.40;
use experimental 'class';

class Account {
    field $owner :param;
    field @log;
    ADJUST { push @log, "opened for $owner" }
    method history { @log }
}
say for Account->new(owner => 'ann')->history;opened for ann

Inheritance and private methods

Perl 5.42+

my method declares a lexical method that code outside the class cannot call, and ->& invokes it. Both are new in Perl 5.42.

use v5.42;
use experimental 'class';

class Shape {
    field $name :param :reader;
    my method label { "<$name>" }
    method describe { $self->&label . ' ' . $self->area }
    method area { 0 }
}
class Square :isa(Shape) {
    field $side :param;
    method area { $side ** 2 }
}
say Square->new(name => 'sq', side => 3)->describe;<sq> 9

Modules & CPAN

Use and install modules

Load modules

use Module () loads a module without importing anything, so you call its functions with the full name.

use v5.40;
use List::Util qw(sum0);
use POSIX ();
use JSON::PP;

say sum0();
say POSIX::floor(2.7);
say JSON::PP->new->canonical->encode({ b => 1, a => [1, 2] });0
2
{"a":[1,2],"b":1}

Install from CPAN

cpanm comes from the App::cpanminus distribution. Installing into a project directory, or with local::lib or Carton, keeps each project's modules apart from the system Perl.

$ cpanm Mojolicious                 # install a module
$ cpanm --installdeps .             # install what cpanfile lists
$ cpanm -l local Path::Tiny         # install into ./local
$ perl -Ilocal/lib/perl5 app.pl
$ perl -MPath::Tiny -e 'print Path::Tiny->VERSION, "\n"'

Write a small module

The file path matches the package name: My::Greeting lives in My/Greeting.pm. The final 1 is the true value require expects. Load it with use lib 'lib'; use My::Greeting qw(hello);.

lib/My/Greeting.pm
package My::Greeting;
use v5.40;
use Exporter 'import';
our @EXPORT_OK = qw(hello);

sub hello ($name) { "Hello, $name" }

1;

Useful core modules

ModuleFor
List::Utilsum, max, min, first, any, all, uniq, shuffle, reduce
Scalar::Utilblessed, reftype, looks_like_number, weaken
Data::DumperPrinting data structures
JSON::PPJSON encoding and decoding
HTTP::TinyHTTP requests
File::Spec, File::Basename, File::Path, File::TempPaths and temporary files
Getopt::LongCommand line options
Time::Piece, POSIXDates and strftime
Test::MoreUnit tests
StorableDeep copies and serialization

builtin Functions

Functions in the builtin namespace

Imported by use v5.40

Perl 5.40+

use v5.40 imports the stable builtins: true, false, blessed, refaddr, reftype, ceil, floor, trim, indexed and a few more. Others, such as is_bool, are still experimental and must be called as builtin::is_bool.

use v5.40;

say true ? 'true' : 'false';
say ceil(1.2), ' ', floor(-1.2);
say '[', trim("  padded  "), ']';
say reftype([]), ' ', blessed(bless {}, 'Foo');
say refaddr([]) =~ /^\d+$/ ? 'refaddr is a number' : 'no';true
2 -2
[padded]
ARRAY Foo
refaddr is a number

Call them by full name on 5.36 and 5.38

use v5.36;
no warnings 'experimental::builtin';

say builtin::trim("  x  ");
say builtin::true;x
1

Sorting

Sort lists

Numeric, reverse and case-insensitive

Plain sort compares as strings, so 100 comes before 9. Use <=> for numbers. $a and $b are special package variables; never declare them with my.

use v5.40;

my @n = (10, 9, 100, 1);
say join ' ', sort @n;
say join ' ', sort { $a <=> $b } @n;
say join ' ', sort { $b <=> $a } @n;
say join ' ', sort { lc $a cmp lc $b } qw(banana Apple cherry);1 10 100 9
1 9 10 100
100 10 9 1
Apple banana cherry

Sort by several keys

or moves on to the next key when the first comparison returns 0.

use v5.40;

my @people = (['ann', 31], ['bob', 27], ['al', 31]);
for my $p (sort { $b->[1] <=> $a->[1] or $a->[0] cmp $b->[0] } @people) {
    say "$p->[0] $p->[1]";
}al 31
ann 31
bob 27

Sort by an expensive key, computed once

This is the Schwartzian transform: compute each key once, sort on it, then throw the keys away.

use v5.40;

my @files = ('b.txt:300', 'a.txt:20', 'c.txt:1000');
my @sorted = map  { $_->[1] }
             sort { $a->[0] <=> $b->[0] }
             map  { [ (split /:/)[1], $_ ] } @files;
say "@sorted";a.txt:20 b.txt:300 c.txt:1000

Dates & Time

Dates and times

Epoch seconds and formatting

gmtime and localtime return a list in which the year counts from 1900 and the month from 0, which is why the +1900 and +1 are needed. Use localtime for the machine's time zone.

use v5.40;
use POSIX qw(strftime);

my $t = 1796256000;
say strftime('%Y-%m-%d %H:%M:%S', gmtime $t);
my @parts = gmtime $t;
say $parts[5] + 1900, '-', $parts[4] + 1;
say scalar gmtime $t;2026-12-03 00:00:00
2026-12
Thu Dec  3 00:00:00 2026

Parse and compare dates with Time::Piece

use v5.40;
use Time::Piece;
use Time::Seconds;

my $d = Time::Piece->strptime('2026-12-02', '%Y-%m-%d');
say $d->strftime('%A, %d %B %Y');
my $later = $d + 30 * ONE_DAY;
say $later->ymd;
my $diff = Time::Piece->strptime('2027-01-01', '%Y-%m-%d') - $d;
say int($diff->days), ' days';Wednesday, 02 December 2026
2027-01-01
30 days

Commands, Arguments & Environment

Run other programs

system, backticks and exit codes

Pass system a list to avoid the shell and its quoting problems. The exit status is in $?, shifted left by 8 bits.

use v5.40;

my $out = qx{echo hello};
print "captured: $out";
system('sh', '-c', 'exit 3');
say 'exit code ', $? >> 8;
my @lines = `printf 'a\nb\n'`;
say scalar @lines;captured: hello
exit code 3
2

Arguments and the environment

use v5.40;

local @ARGV = ('--verbose', 'input.txt');
say scalar @ARGV, ' args, first is ', $ARGV[0];
$ENV{APP_MODE} = 'test';
say $ENV{APP_MODE};
say exists $ENV{HOME} ? 'HOME is set' : 'no HOME';2 args, first is --verbose
test
HOME is set

Parse options with Getopt::Long

=s takes a string, @ collects repeated options and | adds an alias. What is left in @ARGV after GetOptions are the plain arguments.

use v5.40;
use Getopt::Long;

local @ARGV = ('--name', 'ann', '-v', '--tag', 'a', '--tag', 'b', 'file.txt');
my %o = (name => 'world', tag => []);
GetOptions(\%o, 'name=s', 'v|verbose', 'tag=s@') or die "bad options\n";
say "name=$o{name} verbose=$o{v} tags=@{$o{tag}} rest=@ARGV";name=ann verbose=1 tags=a b rest=file.txt

Read from standard input or files named on the command line

The empty <> reads the files named in @ARGV one after another, or standard input when there are none, which makes any script work in a pipe.

#!/usr/bin/env perl
use v5.40;

while (my $line = <>) {
    chomp $line;
    say length($line), " $line";
}

JSON & HTTP

JSON

Decode and encode

canonical sorts keys, so the output is stable. decode_json expects UTF-8 bytes; JSON::XS and Cpanel::JSON::XS are faster drop-in choices from CPAN.

use v5.40;
use JSON::PP;

my $json = JSON::PP->new->utf8->canonical->pretty;
my $data = decode_json('{"name":"Ann","tags":["dev","ops"],"admin":true}');
say $data->{tags}[1];
say $data->{admin} ? 'admin' : 'user';
$data->{age} = 31;
print $json->encode($data);ops
admin
{
   "admin" : true,
   "age" : 31,
   "name" : "Ann",
   "tags" : [
      "dev",
      "ops"
   ]
}

HTTP

GET and POST with HTTP::Tiny

HTTP::Tiny is in core but needs IO::Socket::SSL and Net::SSLeay for https. For anything bigger, Mojo::UserAgent and LWP::UserAgent are the usual choices.

use v5.40;
use HTTP::Tiny;
use JSON::PP;

my $http = HTTP::Tiny->new(timeout => 10);
my $res = $http->get('https://api.github.com/repos/Perl/perl5');
die "HTTP $res->{status}\n" unless $res->{success};
say decode_json($res->{content})->{full_name};

my $post = $http->post('https://httpbin.org/post', {
    headers => { 'Content-Type' => 'application/json' },
    content => encode_json({ ping => 1 }),
});
say $post->{status};

Debugging & Testing

Debug

Check, warn and step through

Deparse shows how Perl parsed your code, which settles most precedence arguments.

$ perl -c app.pl                 # syntax check only
$ perl -w app.pl                 # warnings even without use warnings
$ perl -d app.pl                 # interactive debugger
$ perl -MO=Deparse -e 'print for 1..3'

Debugger commands

CommandDoes
nNext line, stepping over subs
sStep into a sub
c or c 42Continue, or continue to line 42
b 42 or b subnameSet a breakpoint
p $x and x $refPrint a value, dump a structure
lList the code around the current line
qQuit

Test

Test::More

t/basic.t
use v5.40;
use Test::More;

sub add ($x, $y) { $x + $y }
is add(2, 3), 5, 'adds';
ok add(1, 1) == 2, 'one plus one';
is_deeply [sort { $a <=> $b } 3, 1, 2], [1, 2, 3], 'sorts numbers';
like 'error: timeout', qr/timeout/, 'mentions timeout';
done_testing;ok 1 - adds
ok 2 - one plus one
ok 3 - sorts numbers
ok 4 - mentions timeout
1..4

Run the tests and tidy the code

prove ships with Perl. perltidy and perlcritic come from CPAN.

$ prove -l t/              # run every .t file, with lib/ on the path
$ prove -lv t/basic.t      # verbose
$ perltidy -b app.pl       # reformat in place
$ perlcritic app.pl        # lint against best practices

Errors & Gotchas

Error messages

What the common messages mean

MessageUsually means
Global symbol "$x" requires explicit package nameA variable without my, or a typo in its name
Use of uninitialized value $x in concatenation$x is undef; check where it is set or use //
Can't locate Foo/Bar.pm in @INCThe module is not installed, or its lib directory is not in @INC
Can't call method "x" on an undefined valueThe object variable is undef
Not an ARRAY referenceYou dereferenced a hash or scalar as an array
Odd number of elements in hash assignmentA list with a missing value was assigned to a hash
Argument "abc" isn't numericA string was used as a number
Too many arguments for subroutineA signature got more arguments than it accepts

Gotchas

Context changes the result

An array in scalar context gives its length. Parentheses on the left make a list assignment, which takes the first element instead.

use v5.40;

my @a = (5, 6, 7);
my $count = @a;
my ($first) = @a;
say "$count $first";
my $last = (5, 6, 7)[-1];
say $last;
say 'items: ' . @a;3 5
7
items: 3

Numbers and strings compare differently

use v5.40;
no warnings 'numeric';

say '10' == 10.0 ? 'equal as numbers' : 'different';
say '10' eq '10.0' ? 'equal as strings' : 'different as strings';
say 'abc' == 0 ? 'abc is 0 as a number' : 'not 0';equal as numbers
different as strings
abc is 0 as a number

Perl 5.36 to 5.44

Release history

What each release added

Perl releases a stable version every year, with even minor numbers; odd numbers such as 5.45 are development releases. The two most recent stable series get bug and security fixes, so upgrade at least every second year.

VersionReleasedMain additions
5.44July 2026Named parameters in signatures (experimental), multi-variable foreach with reference aliases, Unicode 17
5.42July 2025any and all keywords, :writer fields, lexical methods with my method and ->&, ^^=
5.40June 2024try/catch stable, builtin stable, ^^ logical xor, :reader fields, __CLASS__, use v5.40 imports builtins
5.38July 2023Experimental class syntax with field, method and ADJUST, //= and `=` signature defaults
5.36May 2022use v5.36 turns on strict, warnings and signatures; stable signatures, isa, boolean tracking

What Is a Perl Cheat Sheet

A Perl cheat sheet is a compact reference to Perl's syntax, built-in functions, regular expressions and command line switches, arranged so you can find the right way to sort a hash, split a line or open a file without searching through perldoc. People also look for a Perl quick reference or Perl syntax cheat sheet; they usually need it while maintaining an existing script, writing a one-liner, or reading code written years ago in an older style.

This one has 24 sections and 103 rows. It is written in modern Perl, starting every example with use v5.40;, and still shows the classic forms, such as @_ and bless-based objects, that fill most existing code. Every example with an output was run on Perl 5.42.2 and the output under it is what it printed. Rows that need a newer Perl than 5.10 name the version, and the version picker next to the search box hides what your Perl cannot run.

How It Differs From perldoc

Perl's documentation is excellent and enormous: perlfunc alone describes more than two hundred functions. This page picks the forms you use every day, shows each one as a complete program you can paste and run, and puts the gotchas, such as context, string versus number comparison and hash order, next to the code where they bite. When you need the full story, the perldoc commands in the first section take you straight to the right page.


What This Perl Cheat Sheet Covers


Perl Syntax Quick Reference

TaskPerl
Start a scriptuse v5.40;
Scalar, array, hashmy $s; my @a; my %h;
Array element, hash value$a[0], $h{key}
Array lengthscalar @a
Last element$a[-1]
Appendpush @a, $x
Key existsexists $h{key}
Loop over a listfor my $x (@a) { ... }
Loop over a hashfor my $k (sort keys %h) { ... }
String equality$a eq $b
Number equality$a == $b
Concatenate$a . $b
Default if undef$x // 'default'
Sub with signaturesub add ($x, $y) { $x + $y }
Array referencemy $r = [1, 2]; $r->[0]
Hash referencemy $r = { k => 1 }; $r->{k}
Match and capturemy ($n) = $s =~ /(\d+)/;
Replace all$s =~ s/old/new/g;
Split and joinsplit /,/, $s, join ',', @a
Read a fileopen my $fh, '<', $path or die $!;
Catch an errortry { ... } catch ($e) { ... }
Print with a newlinesay $x;

What Perl Is

Perl is a general-purpose scripting language that Larry Wall released in 1987, at first as a better tool for reporting on text files than the shell, sed and awk of the time. It grew into the glue language of early web development and system administration, and the regular expression syntax it popularized became PCRE, which most languages and tools now use. Perl 5, first released in 1994, is still the living language: a new stable version comes out every year, and Perl 5.44 is the current one. The official documentation for every version is on perldoc.perl.org.

Raku, which was called Perl 6 until 2019, is a separate language. Perl 7 was announced in 2020 as a version of Perl 5 with modern defaults; that plan turned into the use v5.36 and later bundles, which give you the same defaults with one line.

Where Perl Fits Today

Perl shines where text meets the system: parsing logs, rewriting config files, gluing command line tools together, generating reports and transforming data formats. It is preinstalled on nearly every Linux distribution and macOS, which makes Perl scripts the safe choice for tools that must run anywhere without installing a runtime. Large Perl code bases still run banking, airline, publishing and genomics systems, so reading Perl remains a valuable skill even for teams that write new services in other languages.

For new back-end development, Perl's Mojolicious and Dancer2 frameworks are pleasant to use, though Python and Go have larger hiring pools. If you are deciding between them, the Python cheat sheet shows the same tasks in Python. For the shell side of Perl work, see the Bash cheat sheet, the Linux commands cheat sheet and the regex cheat sheet.


Perl, Python and Bash Compared

TaskPerlPythonBash
Print matching linesperl -ne 'print if /x/'a short scriptgrep x
Replace in a fileperl -pi -e 's/a/b/g'a short scriptsed -i 's/a/b/g'
Regex syntaxBuilt into the languageThe re modulegrep -E, =~ in [[ ]]
Dictionary%hdictdeclare -A
Package managerCPAN, cpanmPyPI, pipNone
Preinstalled on Linux and macOSYesUsuallyYes

Common Perl Mistakes

  • Comparing strings with ==. Use eq for strings; == converts both sides to numbers, so 'abc' == 'xyz' is true.
  • Forgetting context. my $n = @a gives the length, my ($n) = @a the first element.
  • Printing a hash and expecting order. Keys come out in a different order on each run; sort them.
  • Leaving out use strict. Without it, typos create new variables silently. use v5.36 and later turn strict on.
  • Two-argument open. open FH, $file treats characters such as > or | in the file name as instructions. Use three arguments and a lexical handle.
  • Not checking open. Always add or die "...: $!".
  • Sorting numbers with plain sort. It sorts as strings; use sort { $a <=> $b }.
  • Declaring $a or $b with my. They are reserved for sort blocks.

How to Learn Perl Today

Start Modern

Begin every script with use v5.40; so strict, warnings, say, signatures and try/catch are on from the first line, and read perldoc perlintro once from start to end; it takes about half an hour. Then practise context, references and regular expressions until they feel natural, because those three explain most of the Perl code you will read.

Then Read Old Code

Most Perl you meet at work predates signatures and the class feature. Learn to read my ($x, $y) = @_;, bless-based objects and two-argument open, and refactor them gradually; small, careful code refactoring with tests in place is how old Perl code bases stay healthy.


How This Perl Cheat Sheet Is Maintained

Every example with output was run on Perl 5.42.2 by a script that extracts each snippet from the page, runs it and puts the real output under it, so a change in behaviour shows up the next time the page is built. Version notes were checked against the perldelta documents for Perl 5.36 to Perl 5.44. The page is reviewed after each yearly stable release.

Sources: perlintro, perlfunc, perlop, perlre, perlsub, perlclass, perlrun and the perldelta documents for Perl 5.36, 5.38, 5.40, 5.42 and 5.44.


Perl Questions People Actually Ask

Is Perl still used in 2026?

Yes. Perl runs a large share of system scripts, build and packaging tools, bioinformatics pipelines, finance back ends and long-lived web applications, and it ships with almost every Linux and macOS system. New projects pick it less often than Python, but a new stable release still comes out every year, and Perl 5.44 arrived in July 2026.

What is the latest version of Perl?

Perl 5.44.0, released in July 2026, is the latest stable version. It adds experimental named parameters in subroutine signatures and Unicode 17. Odd minor versions such as 5.45 are development releases. Perl 7 was announced in 2020 but has not been released; the language continues as Perl 5.x.

What does my mean in Perl?

my declares a lexical variable that exists only inside the enclosing block or file. With use strict, which use v5.36 and later turn on, every variable must be declared with my, our or state, so a typo in a variable name becomes a compile error instead of a silent new global.

What is the difference between an array and a hash in Perl?

An array is an ordered list indexed by number, written with @ and accessed as $a[0]. A hash maps string keys to values, written with % and accessed as $h{key}. Hash order is not defined, so sort the keys when the order of the output matters.

How do I use regular expressions in Perl?

Match with $string =~ /pattern/ and read captures from $1, $2 or named captures from %+. Replace with s/old/new/, add g for every match and r to return a new string instead of changing the old one. Perl's regex syntax became the model for PCRE, so most other languages use the same patterns.

What are Perl one-liners?

One-liners are small Perl programs run straight from the shell with perl -e. Switches such as -n and -p loop over input lines, -i edits files in place, -a splits lines into fields and -l handles newlines, which makes Perl a stronger replacement for grep, sed and awk in a pipeline.

Does Perl have classes?

Yes, in two ways. Classic Perl objects are hash references blessed into a package, which is how most CPAN modules work. Since Perl 5.38 there is also an experimental class syntax with class, field, method and ADJUST, extended in 5.40 and 5.42 with :reader and :writer accessors and lexical methods.

What is the difference between Perl and Python?

Both are general-purpose scripting languages. Perl has stronger built-in text processing, regular expressions in the core syntax and very short command line one-liners, while Python has a simpler syntax, a larger data science and machine learning ecosystem and is more often taught first. Many sysadmins use both.

Is this Perl cheat sheet up to date?

Yes. It was checked on December 2, 2026 against the documentation for Perl 5.36 to Perl 5.44. Every example with output was run on Perl 5.42.2, and the version picker hides rows that need a newer Perl than the one you run.

Can I download this Perl cheat sheet as a PDF?

Yes. Use your browser's print command and choose Save as PDF. The print layout keeps every snippet, output and explanation and leaves out the search box, navigation and tools. Run a search or pick a Perl version first to print only the rows that are still visible.