Perl Cheatsheet

Regular Expressions

Use this Perl reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Match Operator

if ($text =~ /error/) { print "found\n"; }
if ($text !~ /error/) { print "clean\n"; }

Common Pattern Tokens

TokenMeaning
.any char except newline
\ddigit
\Dnon-digit
\wword char
\swhitespace
^start
$end
*zero or more
+one or more
?zero or one
{m,n}between m and n repeats
[abc]one listed char
[^abc]one char not listed

Flags

/text/i                      # case-insensitive
/text/m                      # ^ and $ match line boundaries
/text/s                      # . can match newline
/text/x                      # allow whitespace and comments in regex
/text/g                      # global matching

Captures

my $email = "ada\@example.com";
my ($user, $domain) = $email =~ /^([^@]+)@(.+)$/;

if ($date =~ /(\d{4})-(\d{2})-(\d{2})/) {
    my ($year, $month, $day) = ($1, $2, $3);
}

Named Captures

if ($date =~ /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/) {
    print "$+{year}/$+{month}/$+{day}\n";
}

%+ holds the named captures of the last successful match.

qr// Compiled Patterns

my $num_re = qr/\d+(?:\.\d+)?/;      # compile once, reuse anywhere
my $err_re = qr/error/i;             # flags travel with the pattern

if ($line =~ /^$num_re$/) { ... }    # interpolates as a sub-pattern
my @bad = grep { /$err_re/ } @lines;

Substitution

$s =~ s/foo/bar/;            # first occurrence
$s =~ s/foo/bar/g;           # all occurrences
my $new = $s =~ s/foo/bar/gr;  # /r returns a modified copy, $s unchanged
$s =~ s/^\s+|\s+$//g;       # trim edges
$s =~ s/\s+/ /g;            # collapse whitespace
$s =~ s/(\d+)/$1 * 2/ge;    # /e evaluates the replacement as code

tr/// Transliteration

$s =~ tr/a-z/A-Z/;                 # uppercase in place, char by char
my $upper = $s =~ tr/a-z/A-Z/r;    # /r returns a copy
my $vowels = ($s =~ tr/aeiou//);   # empty replacement just counts
$s =~ tr/0-9//cd;                  # /c complement + /d delete: keep only digits

Global Extraction

my @numbers = $text =~ /\d+/g;
while ($text =~ /(\w+)=(\w+)/g) {
    print "$1 -> $2\n";
}

Regex Split

my @fields = split /\s*,\s*/, "a, b, c";
my @words = split ' ', $line;      # split ' ' strips leading whitespace