On Thu, Nov 13, 2025 at 02:40:28PM +0300, Maksim Rodin wrote:
> Hello,
> There seems to be a typo in perldoc perlretut:
> """ Named backreferences ...
> Outside of the pattern a named capture group is accessible through the "%+"
> hash. """
>
> But in the following example the capture groups (d, m, y) are referenced by
> "$+"
> hash:
> $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
> $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
> $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
> for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
> if ( $d =~ m{$fmt1|$fmt2|$fmt3} ) {
> print "day=$+{d} month=$+{m} year=$+{y}\n";
> }
> }
> or I got something wrong.
You got something wrong :-).
Try the following version:
#!/usr/bin/perl
$fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
$fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
$fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
if ( $d =~ m{$fmt1|$fmt2|$fmt3} ) {
print ("day=".%+{d}." month=".%+{m}." year=".%+{y}."\n");
}
}
But you can also use the $name_of_a_hash syntax to access individual elements
as you have seen.
Also note that printing the contents of % elements directly will prepend the
hash key to the output:
#!/usr/bin/perl
$fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
$fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
$fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
if ( $d =~ m{$fmt1|$fmt2|$fmt3} ) {
print %+{d};
print "\n";
print $+{d};
print "\n";
}
}