Next | Higher-Order Parsing | 31 |
Parsing arithmetic-type expressions is not too uncommon
A useful utility is an operator function:
$expression = operator($Term, [lookfor(['OP', '+']), sub { $_[0] + $_[1] }], [lookfor(['OP', '-']), sub { $_[0] - $_[1] }]);
$term = operator($Factor, [lookfor(['OP', '*']), sub { $_[0] * $_[1] }], [lookfor(['OP', '/']), sub { $_[0] / $_[1] }]);
This little bit of code writes a function that parses an input like 2 + 3 * 4 and calculates the result (14)
For technical reasons, getting - and / to work requires some tricks
The complications are encapsulated inside of operator
We don't have to worry about them
Next | Copyright © 2007 M. J. Dominus |