perlregexp-grammars

Perl: Regexp::Grammars


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

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 output.

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

As far I see it is working correctly. The MATCH in the tokens is just for me to have bit better debugging.

But I am not sure with 2 points.

Thanks for help!

Best regards, chris


Solution

  • Just found out that is is the print in the root-rule that causes the 1. Seems it is more a return-issue. But its also working with the MATCH= assign if it is the last command.