Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 43 ยท Practice and Review

Perl Cheat Sheet

A compact Perl cheat sheet: variables, operators, special variables, regex, file I/O, references, sprintf formats, one-liner flags and everyday modules.

This page is a quick reference for the Perl you use every day: syntax at a glance, special variables, regular expressions, file operations, one-liner flags and a short list of modules worth knowing. It is built for looking things up, so it is dense on purpose. Each section links to the lesson that explains the topic.

Perl is not installed on this site, so the Perl code is read-only. The commands and outputs marked as output were run on a real Perl 5.42. The two interactive examples are stand-ins in Python and Bash that show the same ideas.

Eight things to remember

Sigils $ scalar, @ array, % hash.
Context Scalar or list changes the result.
Operators == and eq are different.
Default $_ Many functions use it implicitly.

Start every file with use v5.36;

1 / 2

File boilerplate

PERL
#!/usr/bin/env perl
use v5.36;            # strict, warnings, say, signatures
use utf8;             # the source file contains UTF-8 text
binmode STDOUT, ':encoding(UTF-8)';

Run with perl file.pl. Check syntax with perl -c file.pl, read documentation with perldoc perlop or perldoc -f sprintf. See install and run.

Variables and data

Syntax Meaning
my $x = 5; Lexical scalar
my @a = (1, 2, 3); Array
my %h = (a => 1, b => 2); Hash
$a[0], $a[-1], $#a First element, last element, last index
scalar @a Number of elements
@a[1, 2] Array slice
$h{a}, @h{qw(a b)} Hash element, hash slice
qw(a b c) List of words
\@a, \%h, \&f Reference to array, hash, sub
[1, 2], { a => 1 }, sub { ... } Anonymous array, hash, sub
$r->[0], $r->{a}, $c->(1) Follow a reference
@$r, %$r, $r->@*, $r->%* Dereference whole structure
undef $x, defined $x Clear and test a value

Strings in double quotes interpolate $x, @a, $h{a} and \n. Strings in single quotes do not. q(...) and qq(...) are the same with other delimiters. See scalars and arrays.

Operators

Kind Operators
Arithmetic + - * / % **
Numeric compare == != < > <= >= <=>
String compare eq ne lt gt le ge cmp
String . (join), x (repeat)
Logic && || ! // and or not
Assign = += -= *= /= .= x= ||= //= &&=
Range 1 .. 10, 'a' .. 'e'
Increment ++ -- (also $s++ on strings: aa becomes ab)

The defined-or // picks the right side only when the left is undef, which makes it safer than || for values that may be 0 or empty. See operators.

False values: undef, '', 0 and '0'. Everything else is true, including '00', '0.0' and ' '.

Control flow

PERL
if    ($n < 0)  { say 'negative' }
elsif ($n == 0) { say 'zero' }
else            { say 'positive' }

say 'big' if $n > 100;          # statement modifiers
say 'ok'  unless $error;

for my $i (1 .. 5)   { next if $i == 2; last if $i == 4; say $i }
foreach my $item (@list) { ... }
while (my $line = <$fh>) { ... }
until ($done) { ... }

my $label = $n > 5 ? 'high' : 'low';   # ternary
OUTER: for my $x (1..3) { for my $y (1..3) { next OUTER if $y == 2 } }

last leaves a loop, next goes to the next round, redo repeats the current round. See conditionals and loops.

Subroutines

PERL
sub add ($x, $y = 0) { return $x + $y }       # signatures
my $total = add(2, 3);

sub context { return wantarray ? 'list' : 'scalar' }

my $counter = do { my $n = 0; sub { ++$n } }; # closure
use feature 'state';
sub next_id { state $id = 0; return ++$id }

@_ aliases the caller's variables. our declares a package variable, local temporarily replaces a global's value. See subroutines and scope and closures.

Lists and hashes

PERL
push @a, 4;  pop @a;  unshift @a, 0;  shift @a;
my @removed = splice(@a, 1, 2, 'x');    # offset, length, replacement
my @sorted  = sort { $a <=> $b } @nums;  # numeric
my @by_name = sort { lc($a) cmp lc($b) } @names;
my @doubled = map { $_ * 2 } @nums;
my @odd     = grep { $_ % 2 } @nums;
my @rev     = reverse @a;
my $csv     = join ',', @a;
my @parts   = split /,/, $csv;           # split ' ' trims leading space

exists $h{k};  delete $h{k};
for my $k (sort keys %h) { say "$k=$h{$k}" }
while (my ($k, $v) = each %h) { ... }
my %inverse = reverse %h;
$count{$_}++ for @words;

A run of the slicing, splice and utility functions printed:

PERL
my @a = (10 .. 15); my %h = (a => 1, b => 2, c => 3);
say "@a[1,2] @a[-2,-1] @h{qw(a c)}";
my @b = (1 .. 6); my @r = splice(@b, 1, 2, 'x'); say "@b | @r";
TEXT
11 12 14 15 1 3
1 x 4 5 6 | 2 3

split /,/, "a,b,,c,," drops the trailing empty fields and gives a|b||c when joined with |, while a limit of -1 keeps them and gives 6 fields. See list functions and hashes.

Strings and formatting

Function Purpose
length, uc, lc, ucfirst, lcfirst Size and case
substr($s, 2, 3) Part of a string; assignable
index($s, 'x'), rindex Find a substring (-1 if absent)
reverse (scalar context) Reverse a string
chomp, chop Remove trailing newline or last character
sprintf, printf Formatted text
sort, join, split, x Combine and split

Common sprintf formats: %d integer, %s string, %f float, %e scientific, %x hex, %o octal, %% percent. Flags: - left-align, 0 zero-pad, + show sign, and a width or .precision such as %8.2f. A run of printf("%05.1f|%-6s|%+d|%x|%o|%e|%3d%%\n", 3.14159, "ab", 5, 255, 8, 12345.678, 50) printed:

TEXT
003.1|ab    |+5|ff|10|1.234568e+04| 50%

A here-document is a multi-line string. <<"END" interpolates variables and <<'END' does not. See strings and text processing.

Regular expressions

Syntax Meaning
$s =~ /pat/ Test a match
my ($a, $b) = $s =~ /(\d+)-(\d+)/; Captures into a list
$1, $2, %+ Capture variables, named captures (?<name>...)
$s =~ s/old/new/g Substitute
my $t = $s =~ s/old/new/gr; Substitute and return the copy
$s =~ tr/a-z/A-Z/ Transliterate; with an empty replacement it counts
my @all = $s =~ /\d+/g; All matches
my $n = () = $s =~ /x/g; Count matches
qr/pat/i Precompiled pattern
Modifier Effect
/i Ignore case
/g Global: all matches, continues from pos
/m ^ and $ match at each line
/s . matches a newline too
/x Allow spaces and comments in the pattern
/e Evaluate the replacement as code
/r Return the modified copy
Pattern Matches
. \d \w \s Any character (not newline), digit, word character, whitespace
\D \W \S The opposites
[abc] [^abc] [a-z] A set, not in a set, a range
* + ? {2,5} Zero or more, one or more, optional, counted
*? +? ?? Lazy versions
^ $ \A \z \b Line start and end, string start and end, word boundary
(...) (?:...) | Capturing group, non-capturing group, alternation
(?=...) (?!...) (?<=...) (?<!...) Lookahead and lookbehind

For strict validation use \A ... \z, since $ also matches before a final newline. See regex basics, captures and modifiers, substitution and tr and advanced regex.

Files and directories

PERL
open my $in,  '<',  $file or die "Cannot read $file: $!";
open my $out, '>',  $file or die "Cannot write $file: $!";    # truncate
open my $app, '>>', $file or die "Cannot append $file: $!";
open my $utf, '<:encoding(UTF-8)', $file or die $!;

while (my $line = <$in>) { chomp $line; ... }   # line by line
my @lines = <$in>;                               # all lines
my $text  = do { local $/; <$in> };              # whole file
print {$out} "text\n";
close $in;
Test True when
-e $p Exists
-f $p / -d $p Is a plain file / a directory
-r -w -x $p Readable, writable, executable
-s $p Size in bytes (true if not empty)
-M $p Age in days

Other tools: unlink, rename, mkdir, rmdir, opendir/readdir/closedir, glob('*.txt'), and the modules File::Basename, File::Spec, File::Path, File::Find, File::Temp. See file I/O and directories and file tests.

Errors, modules and objects

PERL
my $ok = eval { risky(); 1 };
die "Failed: $@" unless $ok;
die { code => 404 };                  # exceptions can be references
warn "careful\n";

use List::Util qw(sum max min first uniq);
package Point { sub new ($class, %a) { bless {%a}, $class } sub x ($s) { $s->{x} } }
my $p = Point->new(x => 1);
say $p->x;   say ref $p;   say $p->isa('Point') ? 'yes' : 'no';

use Module runs at compile time and imports names. require Module loads at runtime. Search paths are in @INC. See errors, packages and modules, classes and objects.

Special variables

Variable Meaning
$_ Default input and loop variable
@_ Subroutine arguments (aliases)
$0 Program name
@ARGV, %ENV Command-line arguments, environment
$! Last system error (as text or number)
$@ Last eval error
$. Line number of the last file read
$/ Input record separator (default newline)
$, and $\ Output field separator and output record separator
$" Separator used when an array is interpolated (default space)
$1, $&, %+ Regex captures, whole match, named captures
$$ Process ID
$^O, $] Operating system name, Perl version number
STDIN, STDOUT, STDERR Standard handles

Setting $, to - and $\ to !\n makes print 1,2,3 print 1-2-3!, and setting $" to : makes "@a" for (1, 2) print 1:2; both were checked on a real run.

One-liner flags

Flag Meaning
-e 'code' Run code from the command line
-n Wrap the code in while (<>) { ... }
-p Like -n but print $_ at the end of each round
-l Chomp input lines and add a newline to each print
-a Autosplit each line into @F (needs -n or -p)
-F: Split on a pattern instead of whitespace
-i.bak Edit files in place, keeping a backup with that suffix
-0777 Slurp each file whole; -00 reads paragraphs
-M / -I Load a module / add a directory to @INC
-c, -w Check syntax only, enable warnings

With a file containing the lines ana 31 perl, ben 27 go and cy 45 perl, these printed:

TEXT
$ perl -ne 'print if /perl/' people.txt
ana 31 perl
cy 45 perl

$ perl -lane 'print $F[0]' people.txt
ana
ben
cy

$ perl -lane '$s += $F[1]; END { print $s }' people.txt
103

$ perl -pe 's/perl/Perl/' people.txt
ana 31 Perl
ben 27 go
cy 45 Perl

$ echo 'a:b:c' | perl -F: -lane 'print $F[1]'
b

See one-liners.

Everyday modules

Module Use
strict, warnings, feature Safety and modern features (all pulled in by use v5.36)
List::Util sum, max, min, first, uniq, shuffle, reduce
Scalar::Util blessed, looks_like_number, weaken, reftype
Data::Dumper Print any data structure for debugging
POSIX strftime, floor, ceil
Time::Piece, Time::Local Dates and times
Getopt::Long Command-line options
File::Basename, File::Spec, File::Temp, File::Find Paths and files
Cwd Current directory
Carp croak and confess for errors from the caller's view
JSON::PP JSON encoding and decoding
HTTP::Tiny Simple HTTP client
Storable Deep copy with dclone
Test::More Unit tests
Time::HiRes Fractions of a second
Moo, Mojolicious, DBI, Path::Tiny, Try::Tiny Popular CPAN modules

Try the ideas in the browser

The regex notation above is shared with many languages. This Python stand-in uses the same patterns for matching, counting, substituting and named captures.

Python Regex cheat sheet in action (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Perl one-liners such as -n, -a and -F read a line, split it into fields and act on them. The awk tool does the same job, so this Bash example mirrors the first, second and fourth one-liners above.

Bash One-liner ideas with awk (Bash stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which one-liner flag combination reads each line, splits it into fields in @F and prints the first field?

    -n loops over the lines, -a autosplits into @F, -l handles newlines and -e supplies the code.
  2. 2. Which pair of operators is correct for comparing two strings for equality and two numbers for ordering?

    eq compares strings for equality and <=> is the numeric three-way comparison (cmp is the string version).
  3. 3. How do you get the whole contents of an open file into one string?

    Setting the input record separator $/ to undef makes the readline operator return the rest of the file in one piece.
  4. 4. What does my $n = () = $s =~ /x/g; store in $n?

    The empty list assignment gives list context to the match, and in scalar context it returns the count of right-hand values.

Summary

  • Start files with use v5.36;, declare variables with my, and open files with three arguments and an error check.
  • Remember the paired operators: == with <=> for numbers, eq with cmp for strings.
  • Use $_, @_, $!, $@, $. and $/ as the special variables you meet daily.
  • Know the regex toolbox: captures, /g, /r, tr, anchors \A and \z, and lazy quantifiers.
  • Use -n, -p, -l, -a, -F and -i to write powerful one-liners.
  • Reach for core modules like List::Util, Getopt::Long, File::Spec and Test::More before inventing your own.

That is the end of the Perl tutorial. Revisit the Practice Exercises or the Perl Interview Questions any time. To go back to the beginning, start at What Is Perl?.