Capture groups in Perl
Capture groups three ways: numbered lists, named %+ entries, and /g harvests.
use strict;
use warnings;
my $date = "2026-08-02";
# a match in list context returns its capture groups
my ($y, $m, $d) = $date =~ /^(\d{4})-(\d{2})-(\d{2})$/;
print "day $d of month $m, $y\n";
my $log = "GET /api/users 200";
if ($log =~ m{^(?<verb>\w+) (?<path>\S+) (?<status>\d+)$}) {
print "$+{verb} $+{path} -> $+{status}\n";
}
# /g in list context collects every match
my @words = "tea for two at ten" =~ /\bt\w+/g;
print "@words\n";
How it works
- In list context the match returns its groups, filling
$y,$m, and$dat once. (?<verb>...)names a group; the match drops it into the%+hash./gin list context collects every match, here one array of all the t-words.
Keywords and builtins used here
ifmyprintuse
The run, in numbers
- Lines
- 17
- Characters to type
- 442
- Tokens
- 64
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 64 seconds.
Step 3 of 3 in Regular expressions, step 9 of 27 in Language basics.