NAME

Math::Expression::Evaluator::Parser - Parse mathematical expressions

SYNOPSIS

use Math::Expression::Evaluator::Parser;
my $exp = '2 + a * 4';
my $ast = Math::Expression::Evaluator::Parser::parse($exp, {});
# $ast is now something like this:
# $ast = ['+',
#          2,
#         ['*',
#          ['$', 'a'],
#          4
#         ]
#        ];

DESCRIPTION

This module parses a mathematical expression in usual notation, and turns it into an Abstract Syntax Tree (AST).

If you want to have a simple interface and want to evaluate these ASTs, use Math::Expression::Evaluator.

The following description of the AST structure matches the current implementation, but really is an implementation detail that's subject to change without further notice. In particular a possible addition of meta information (like file and line numbers) might require a change of structure.

The AST is a tree that consists of nested array refs. The first item is a string (until now always a single character), and denotes the type of the node. The rest of the items in the array is a list of its arguments.

For the mathematical symbols +, -, *, /, ^ (exponentation) this is straight forward, but / and - are always treated as prefix ops, so the string '2 - 3' is actually turned into ['+', 2, ['-', 3]].

Other AST nodes are

'$'

['$', $var_name] represents a variable.

'{'

['{', $expr1, $expr2, ... ] represents a block, i.e. a list of expressions.

'='

['=', $var, $expr] represents an assignment, where $expr is assigned to $var.

'&'

['&', $name, @args] is a function toll to the function called $name.

METHODS

parse

parse takes a string and a hash ref, where the hash ref takes configuration parameters. Currently the only allowed option is force_semicolon. If set to a true value, it forces statements to be forced by semicolons (so 2 3 will be forbidden, 2; 3 is still allowed).

parse throws an exception on parse errors.