regname#
Return the contents of a named capture group from the most recent successful match.
With one argument, returns the first defined value captured by the named group. With a truthy second argument, returns an array reference holding every value the group captured — useful when the same name appears in a repeated subpattern or in multiple alternation branches.
Synopsis#
use re 'regname';
"foobar" =~ /(?<word>\w+)/;
my $first = regname('word'); # 'foobar'
my $all = regname('word', 1); # arrayref of all captures
What you get back#
Without
$all(or with a false$all) — the first defined captured string, orundefif the name didn’t match anything or didn’t exist in the pattern.With a truthy
$all— an array reference containing every captured value for that name, in order.If there was no prior successful match —
undef.
Examples#
"2025-04-22" =~ /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/;
print regname('y'); # '2025'
"abc123" =~ /(?<n>\d+)|(?<n>\w+)/;
print regname('n'); # first defined capture
print join(',', @{ regname('n', 1) }); # every capture for 'n'
my $missing = regname('nope'); # undef — no such name
Edge cases#
Called with zero arguments — croaks with
Usage: re::regname(name [, all]).No successful match yet in the current scope — returns
undef.Name was declared but did not participate in the match — returns
undef(single form) or an arrayref ofundefs ($allform).