Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

5.10 named capture in DEFINE regex

by philcrow (Priest)
on Dec 27, 2007 at 17:04 UTC ( #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
Node Status?
node history
Node Type: perlquestion [id://659220]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
[tye]: No, I write more Perl than py at work. But I have to deal with plenty of py things.
[tye]: py monks would just be offended.
[Corion]: ;)
[Corion]: Hi tye btw ;)
[Corion]: I found plenty of not chatty enough logs with Perl too ... I'm slowly coming to appreciate Log::Log4perl resp. our homegrown alternative
[tye]: my experience with python so far is more like finding a moderately useful error message is a shocking surprise.
Corion disappears

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2017-09-21 20:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    During the recent solar eclipse, I:









    Results (252 votes). Check out past polls.

    Notices?