#!/usr/bin/perl -w use strict; use warnings; use Parse::RecDescent; use Data::Dumper; use FindBin; use lib $FindBin::Bin; use vars qw(%VARIABLE); # Enable warnings within the Parse::RecDescent module. $::RD_ERRORS = 1; # Make sure the parser dies when it encounters an er +ror $::RD_WARN = 1; # Enable warnings. This will warn on unused rules &c +. $::RD_HINT = 1; # Give out hints to help fix problems. my $grammar = <<'_EOGRAMMAR_'; # Terminals (macros that can't expand further) # OP : m([-+*/%]) # Mathematical operators INTEGER : /[-+]?\d+/ # Signed integers VARIABLE : /\w[a-z0-9_]*/i # Variable expression : INTEGER OP expression { return main::expression(@item) } | VARIABLE OP expression { return main::expression(@item) } | INTEGER | VARIABLE { return $main::VARIABLE{$item{VARIABLE}} } print_instruction : /print/i expression { print $item{expression}."\n" } assign_instruction : VARIABLE "=" expression { $main::VARIABLE{$item{VARIABLE}} = $item{expre +ssion} } instruction : assign_instruction | print_instruction | <error> startrule: instruction(s) eofile { $return = $item[1] } eofile: /^\z/ _EOGRAMMAR_ sub expression { shift; my ($lhs,$op,$rhs) = @_; if ( $lhs =~ m/[^-+0-9]/ ) { $lhs = $VARIABLE{$lhs}; } # IF return eval "$lhs $op $rhs"; } # end of expression my $parser = Parse::RecDescent->new($grammar); unless ( defined $parser ) { die("Could not pare the grammar\n$grammar\n"); } # UNLESS my $buffer; while ( 1 ) { print "\nEnter --> "; $buffer = <STDIN>; chomp $buffer; if ( $buffer eq "" || $buffer =~ m/^\s+$/ ) { last; } # IF my $ref = $parser->startrule($buffer); unless ( defined $ref ) { print "Error returned by parsing\n"; } # UNLESS } # WHILE exit 0;
In reply to Re^4: how to match entire buffer with Parse::RecDescent
by expo1967
in thread how to match entire buffer with Parse::RecDescent
by expo1967
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |