Perl Easy · Lesson 1 · On the house

Regex match basics

m//, =~, capture $1, /x light. Lesson 1 is free — on the house.

Lessons · Perl Easy · Lesson 1 of 10 · On the house

Regex match basics

m//, =~, capture $1, /x light.

Illustration for Perl
Lesson 1 is on the house.

Bind a string to a pattern with =~. The match operator is m/pattern/ or just /pattern/. In scalar context, $s =~ /Ada/ is true when $s contains a match.

Parentheses capture: $s =~ /(\w+) (\d+)/ sets $1 to the first group and $2 to the second after a successful match. Captures are reset on the next successful match in the same scope.

The /i flag ignores case. The /x flag lets you write spaced patterns with comments: m/ (\d+) /x still matches digits. Prefer /x when a pattern grows hard to read.

!~ is the negated bind — true when the pattern does not match. Always test success before trusting $1; an unsuccessful match leaves prior captures alone or undef depending on context — check the match first.

Misses: writing match() like Python, using === for regex, reading $1 without a successful =~, or putting the pattern on the left without =~ (/Ada/ =~ $s is wrong orientation for beginners).

regex-match

#!/usr/bin/env perl
use strict;
use warnings;

my $s = "Ada 36";
if ($s =~ /(\w+) (\d+)/) {
    print "name=$1 age=$2\n";
}
print "has-ada\n" if $s =~ /ada/i;
print "spaced\n" if $s =~ / (\d+) /x;
Match this when you type.

Quiz

Which operator binds a string to a regex match?

Quiz

After a successful /(\w+)/ match, where is the capture?

Quiz

What does /i do on a match?

Quiz

What does /x allow in a pattern?

Check

Match the still for: Regex match basics.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.