Perl: Regexp :: Grammars

I tried Regexp :: Grammars and I got 2 problems. Maybe someone can help me.

use strict;
use warnings;
use Regexp::Grammars;

my $gr = 
qr
{       
    <debug: off>
    <warning: off>

    <root>

    <rule: root>
        ^<X=val> <O=op> <Y=val>$
        <MATCH=(?{ 
                if ($MATCH {O} eq "+")
                {
                    $MATCH = $MATCH {X} + $MATCH {Y};
                }
                elsif ($MATCH {O} eq "*")
                {
                    $MATCH = $MATCH {X} * $MATCH {Y};
                } 
                elsif ($MATCH {O} eq "/")
                {
                    $MATCH = $MATCH {X} / $MATCH {Y};
                } 
                print"\nCALC=$MATCH"; 
            })>

    <token: val>
        <X=([0-9]+)>
        <MATCH=(?{ print "\nVAL: " . $MATCH {X}; $MATCH = $MATCH {X}; 
        })>

    <token: op>
        <X=([\+\*\/])>
        <MATCH=(?{ print "\nOP: " . $MATCH {X}; $MATCH = $MATCH {X}; })>
    }xms;

##########################################

my $input = "10 + 3";

if ($input =~ $gr) 
{
    foreach (keys %/)
    {
        print "\nHSH: \"$_\" = " .  $/{$_};
    }
}

      

Here is the result.

VAL: 10
OP: +
VAL: 3
[eos]   \_____<grammar> matched '10 + 3'    
CALC=13
HSH: "" = 10 + 3
HSH: "root" = 1

      

As far as I can see it is working correctly. MATCH in tokens just for me to debug a little better.

But I'm not sure with 2 points.

  • Why does this [eos] line still exist? I disabled debugging.
  • How can I get the result (CALC = 13) in the root element and hence in the hash of the result? I was expecting root = 13.

Thanks for the help!

Regards, Chris

+3


source to share


1 answer


Just found out that it is a seal in the root rule that causes 1. It looks like a more distant problem. But it also works with MATCH = assigns if this is the last command.



+2


source







All Articles