develooper Front page | perl.perl5.porters | Postings from August 2017

(?(DEFINE)) and captures.

Thread Next
From:
Abigail
Date:
August 14, 2017 22:04
Subject:
(?(DEFINE)) and captures.
Message ID:
20170814213933.GA7658@almanda.fritz.box

Here's a pattern which uses a (?(DEFINE)) construct to define a
couple of named rules. Each such rule must consist of a named
capture.


    my $pat_1 = qr {
        (?(DEFINE)
           (?<foo>  foo)
           (?<bar>  (?&foo)))

        (?&bar)
    }x;


Now, if we perform a match with them, do we get captures? If you 
don't know the answer, don't worry, Perl itself doesn't quite
know what to do it with it either:


    "foo" =~ /$pat_1/ or die "No match";

    printf "Got %d different names for captures\n" => scalar keys %-;
    printf "Got %d named captures\n"               => scalar keys %+;
    printf "Got %d captures\n"                     => scalar @{^CAPTURE};

    __END__
    Got 2 different names for captures
    Got 0 named captures
    Got 0 captures


Now, let's see what happens if we add one more set of capturing
parenthesis to the pattern:

    my $pat_2 = qr {
        (?(DEFINE)
           (?<foo>  foo)
           (?<bar>  (?&foo)))

        (
            (?&bar)
        )
    }x;


    "foo" =~ /$pat_2/ or die "No match";

    printf "Got %d different names for captures\n" => scalar keys %-;
    printf "Got %d named captures\n"               => scalar keys %+;
    printf "Got %d captures\n"                     => scalar @{^CAPTURE};

    __END__
    Got 2 different names for captures
    Got 0 named captures
    Got 3 captures


We went from 0 captures to 3! That is, $1 and $2 are undefined, while
$3 is set (to "foo"). No named captures are available though.


I'm sure there's a perfectly good explaination if you know the details
of the implementation, but how do we explain this to users?




Abigail

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About