Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Isn't $1 supposed to contain the thing I matched?

update: The answer is: pattern first (DEFINE) last

#!/usr/bin/perl -- use strict; use warnings; use 5.010; use Data::Dump; my $re = qr{ (?(DEFINE) (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d ) ) # match this ( # save to $1 \b (?&byte) ( \. (?&byte) ){3} \b ) }x; my $str = ' localhost 127.66.66.66 '; while( $str =~ m/$re/g ){ dd( [ $1, \%+, \%-, \%/ ] );#/ } dd([ $str =~ m/$re/g ] ); use Tie::Hash::NamedCapture; tie my %hash, "Tie::Hash::NamedCapture", all => 1; if( $str =~ m/$re/g ){ dd([ $1, \%hash ]); } __END__ [ undef, { # tied Tie::Hash::NamedCapture }, { # tied Tie::Hash::NamedCapture byte => [undef], }, {}, ] [undef, "127.66.66.66", ".66"] [ undef, { # tied Tie::Hash::NamedCapture byte => [undef], }, ]

update: The answer is: pattern first (DEFINE) last

so if I use

my $re = qr{ # match this ( # save to $1 \b (?&byte) ( \. (?&byte) ){3} \b ) (?(DEFINE) (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d ) ) }x;
then $1 is as expected

Replies are listed 'Best First'.
Re: $1 empty with (?(DEFINE)) and (?&NAME)
by tchrist (Pilgrim) on Mar 07, 2012 at 14:22 UTC
    The reason this is happening is that in Perl (well, v5), named groups still participate in being numbered groups. So if you put the DEFINE first, you get the byte group counting as $1.

    I don’t usually try mixing numbered and named group together, because as you see, the numbered ones are fragile.