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

Re: Re: Trying to count the captures in a compiled regular expression

by eric256 (Parson)
on May 03, 2004 at 14:14 UTC ( #350014=note: print w/ replies, xml ) Need Help??


in reply to Re: Trying to count the captures in a compiled regular expression
in thread Trying to count the captures in a compiled regular expression

Could you explain why/how that works?


___________
Eric Hodges


Comment on Re: Re: Trying to count the captures in a compiled regular expression
Explained: Trying to count the captures in a compiled regular expression
by Roy Johnson (Monsignor) on May 03, 2004 at 15:16 UTC
    Upon a successful match, the match operator returns a list of the captures (or, in scalar context, the number of captures), one element for each set of capturing parentheses, even if the captured value is empty. By making the entire pattern optional, we ensure a successful match, and thus Perl will tell us how many groupings were.

    As was pointed out by ysth and hugo, the case of no groupings will not return zero (because we need a true value to indicate a successful match), so we ought to put capturing parentheses around the expression, and subtract one from the result. And the possibility of embedded code, which we wouldn't want to run, is another caveat, so we want to use minimal matching. Hence:

    my $regex = qr/foo/; $_ = 'anything'; my $matches = (() = /($regex)??/) - 1; # oops! fixed print "There were $matches groupings\n";

    The PerlMonk tr/// Advocate
      That runs in scalar context, so won't work; try:
      $matches = (() = /($regex)??/) - 1;
        or even
        /$regex??/; print "There were $#+ groupings\n";

        The PerlMonk tr/// Advocate

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://350014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2014-08-27 09:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (233 votes), past polls