#!/usr/bin/perl use warnings; use strict; use Marpa::R2; use Tree::Binary; package Construct; sub newNode { my ($value, $left, $right) = @_; my $node = Tree::Binary->new($value); $node->setLeft($left) if $left; $node->setRight($right) if $right; return $node; } sub doOp { my @params = @_; return newNode(@params[2, 1, 3],); } sub doConst { my @params = @_; return newNode($params[1]); } package main; my $syntax = <<'SYNTAX'; lexeme default = latm => 1 expression ::= expression '+' term action => doOp | term action => ::first term ::= term '*' factor action => doOp | factor action => ::first factor ::= constant action => doConst constant ~ digits digits ~ [\d]+ :discard ~ spaces spaces ~ [\s]+ SYNTAX my $grammar = Marpa::R2::Scanless::G->new({source => \$syntax}); my $input = '1 * 2 + 3 * 4'; my $root = $grammar->parse(\$input, 'Construct'); ($$root)->traverse(sub {print " " x $_[0]->{_depth}, $_[0]->getNodeValue(), "\n"});