AnyCompiler

Regular Expressions

Every other language on this site treats regular expressions as a library: you import a regex module, construct a pattern object, and call a method on it. Perl builds pattern matching directly into its own syntax. =~ binds a string to a match or substitution; m/pattern/ (the m is optional when using slashes) matches; s/pattern/replacement/ substitutes. There is no import, no object, no method call — it's part of the grammar of the language itself.

use strict;
use warnings;

my $text = "The year 2024 was followed by 2025.";
if ($text =~ /(\d{4})/) {
    print "First match: $1\n";
}

my @years = $text =~ /(\d{4})/g;
print "All years: @years\n";
Output
First match: 2024
All years: 2024 2025

Parentheses in a pattern capture — after a successful match, $1 holds whatever the first parenthesized group matched. The /g flag (global) in list context, as with @years above, returns every match in the string rather than stopping at the first one.

s/pattern/replacement/ substitutes in place on whatever =~ is bound to; adding /g substitutes every occurrence instead of just the first. (my $copy = $sentence) =~ s/.../.../; is the idiomatic way to get a modified copy without disturbing the original string.

use strict;
use warnings;

my $sentence = "cats and cats and cats";
(my $copy = $sentence) =~ s/cats/dogs/;
print "One replaced: $copy\n";

(my $all = $sentence) =~ s/cats/dogs/g;
print "All replaced: $all\n";

if ("hello" =~ /\d/) {
    print "matched\n";
} else {
    print "no digits found\n";
}
Output
One replaced: dogs and cats and cats
All replaced: dogs and dogs and dogs
no digits found

Next: references — how Perl builds nested, non-flat data structures out of its three flat core types.

Practice exercise

Given my $str = "Order #4521 shipped", use a regex match to extract the number and print it.