| Next | Higher-Order Parsing | 29 |
Parsing arithmetic-type expressions is not too uncommon
Higher-Order Perl develops an operator function
From this, one could build an expression_parser function:
$expression =
expression_parser(
ATOM => $ATOM,
OPS => [[lookfor(['^']), sub { $_[0] ** $_[1] }, "right-assoc"],
[lookfor(['*']), sub { $_[0] * $_[1] },
lookfor(['/']), sub { $_[0] / $_[1] }],
[lookfor(['+']), sub { $_[0] + $_[1] },
lookfor(['-']), sub { $_[0] - $_[1] }],
],
);
This little bit of code writes a function that parses an input like 2 + 3 * 4 and calculates the result (14)
It handles precedence, parentheses associativity...
For technical reasons, getting - and / to work requires some tricks
These tricks tend to complicate the design of Parse::RecDescent parsers
With HOP::Parser, the complications are encapsulated inside of operator
| Next | ![]() |
![]() |
Copyright © 2007 M. J. Dominus |