Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

5.10 named capture in DEFINE regex

by philcrow (Priest)
on Dec 27, 2007 at 17:04 UTC ( [id://659220]=perlquestion: print w/replies, xml ) Need Help??

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

I've started playing with the named capture and grammar features of 5.10. I like what I see, but I did find something that stumped me.

If I use a named capture I get what I expect:

#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my $number_re = qr{ (?<int> \d+) }x; my $num = 15; if ( $num =~ /^$number_re$/ ) { warn "'$num' is valid\n"; warn Dumper( \%- ); } # produces: #'15' is valid #$VAR1 = { # 'int' => [ # '15' # ] # };
But, when I try to DEFINE a grammar, the named capture only stores undef:
#!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my $number_re = qr{ (?(DEFINE) (?<int> \d+ ) ) (?&int) }x; my $num = 15; if ( $num =~ /^$number_re$/ ) { warn "'$num' is valid\n"; warn Dumper( \%- ); } # produces: #'15' is valid #$VAR1 = { # 'int' => [ # undef # ] # };
Am I missing something?

(Perhaps my excitement at the new grammar features has raised my expectations too high. I was starting to hope for a parse tree.)

Phil

The Gantry Web Framework Book is now available.

Replies are listed 'Best First'.
Re: 5.10 named capture in DEFINE regex
by brian_d_foy (Abbot) on Dec 27, 2007 at 17:58 UTC

    The results of captures inside the recursion aren't available outside the recursion. See the last paragraph for the DEFINE in perlre. %- will have keys for the names of the bits in DEFINE, but their values will always be undef.

    You need to capture the parts you want and name them yourself (similar to the example in perlre):

    my $number_re = qr{ (?(DEFINE) (?<int_pat> \d+ ) ) (?<int>(?&int_pat)) }x;
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://659220]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-24 20:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found