Captures and named groups
Capture groups
Parentheses in a pattern do two things: they group for quantifiers, and they capture the text that matched. Each pair lands in a numbered variable, starting at $1.
my $date = "2026-10-27";
if ($date =~ /^(\d{4})-(\d{2})-(\d{2})$/) {
print "year $1, month $2, day $3\n";
}
perl demo.pl
year 2026, month 10, day 27
The numbered variables are only reliable right after a successful match. Another pattern anywhere in between overwrites them, which is the most common bug in code that parses several fields.
Captures as a list
In list context a successful match returns the captures directly, which avoids the numbered variables entirely. Assign the result and check it with defined.
my $date = "2026-10-27";
my ($y, $m, $d) = $date =~ /^(\d{4})-(\d{2})-(\d{2})$/;
print "$y/$m/$d\n" if defined $d; # 2026/10/27
perl demo.pl
2026/10/27
A failed match returns an empty list, so the left side variables come out undef. That behavior makes the defined check the natural companion of this style.
Named captures
Numbers get unreadable past three groups. Name each one with (?<name>...) and read it from the %+ hash, where the keys are the names.
my $log = "2026-10-27 ERROR disk full";
if ($log =~ /^(?<date>\S+) (?<level>\w+) (?<msg>.+)$/) {
print "$+{date} [$+{level}] $+{msg}\n";
}
perl demo.pl
2026-10-27 [ERROR] disk full
The same names work in a replacement string, and they keep the pattern self-documenting when a colleague has to change it six months later.
Optional groups
A group followed by a question mark may be missing. It still captures when present, and the variable is undef when absent, which lets one pattern accept several input shapes.
my @lines = ("warning: low", "low");
for my $l (@lines) {
my ($lvl, $msg) = $l =~ /^(?:(\w+):\s*)?(.+)$/;
$lvl //= "info";
print "$lvl - $msg\n";
}
perl demo.pl
warning - low
info - low
The (?:...) form groups without capturing, so the counter for numbered groups stays predictable. Use it for every group you only need for a quantifier.
Next: Substitution with s///
Article author: Arthur Isaev