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


NAME

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


SYNOPSIS


    use Math::Expression::Evaluator::Parser;
    use Math::Expression::Evaluator::Util qw(simplify_ast);
    my $exp = '2 + a * 4';
    my $ast = Math::Expression::Evaluator::Parser::parse($exp, {});
    $ast = simplify_ast($ast);
    # $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 the Math::Expression::Evaluator manpage.

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.


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.