Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Regexp::Grammars what does (*COMMIT) do?

Tags:

perl

I'm looking at an example for Regexp::Grammars. The example has a comment around *COMMIT stating about how it will improve the error messages. I can't find any documentation on *COMMIT. What does it do ? I've included part of the example below:

    use Regexp::Grammars;
qr{ 
    \A 
    <Answer>
    (*COMMIT)   # <-- Remove this to see the error messages get less accurate
    (?:
        \Z
    |
        <warning: (?{ "Extra junk after expression at index $INDEX: '$CONTEXT'" })>
        <warning: Expected end of input>
        <error:>
    )

    <rule: Answer>  
        <[_Operand=Mult]>+ % <[_Op=(\+|\-)]>
            (?{ $MATCH = shift @{$MATCH{_Operand}};
                for my $term (@{$MATCH{_Operand}}) {
                    my $op = shift @{$MATCH{_Op}};
                    if ($op eq '+') { $MATCH += $term; }
                    else            { $MATCH -= $term; }
                }
            })
      |
        <error: Expected valid arithmetic expression>
like image 391
kdubs Avatar asked Apr 07 '26 12:04

kdubs


1 Answers

(*COMMIT) is documented in perlre.

(*COMMIT) is useful in causing an whole alternation to fail when one of the branch fails after reaching a certain point.

$ perl -E'
   say "$_: ", /
      ^
      (?: a (*COMMIT) b
      |   c (*COMMIT) d
      |   . z
      )
   /sx ?1:0
      for qw( ab cd az yz );
'
ab: 1
cd: 1
az: 0
yz: 1

You could have written the following, but it could be far less efficient and far harder to write in more complex examples:

/
   ^
   (?: a b
   |   c d
   |   [^ac] z
   )
/x
like image 73
ikegami Avatar answered Apr 09 '26 09:04

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!