Skip to content
Pattern Matching
step 1/5

Reading — step 1 of 5

Learn

~1 min readRegular Expressions

Perl's regex is legendary — it influenced every modern regex engine. The syntax is built into the language.

Basic match =~ /pattern/:

my $line = "my email is ada@example.com";
if ($line =~ /\w+@\w+/) {
    print "contains an email\n";
}

Capture groups with parentheses, accessed via $1, $2, ...:

if ($line =~ /(\w+)@(\w+\.\w+)/) {
    print "user: $1, domain: $2\n";
}

Modifiers after the closing /:

  • i — case-insensitive
  • g — global (find all)
  • m — multiline (^ and $ match per line)
  • s — dot matches newlines
  • x — allow whitespace and comments in pattern

Substitution s/pattern/replacement/flags:

my $s = "Hello, World!";
$s =~ s/World/Perl/;             # "Hello, Perl!"
$s =~ s/o/0/g;                   # global — "Hell0, P0rl!"

Split and join are sister functions:

my @words = split /\s+/, "hello world foo";
my $joined = join "-", @words;     # "hello-world-foo"

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…