NAME
Parse::BooleanLogic - parser of boolean expressions
SYNOPSIS
my $parser = new Parse::BooleanLogic;
my $tree = $parser->as_array( string => 'x = 10' );
$tree = $parser->as_array( string => 'x = 10 OR (x > 20 AND x < 30)' );
$parser->parse(
string => 'x = 10 OR (x > 20 AND x < 30)',
callback => {
open_paren => sub { ... },
operator => sub { ... },
operand => sub { ... },
close_paren => sub { ... },
error => sub { ... },
},
);
DESCRIPTION
This module is quite fast parser for boolean expressions. Original it's been writen for Request Tracker for parsing SQL like expressions and it's still capable to, but it can be used to parse other boolean logic sentences with OPERANDs joined using binary OPERATORs and grouped and nested using parentheses (OPEN_PAREN and CLOSE_PAREN).
METHODS
as_array
Takes a string and parses it into perl structure, where parentheses represented using array references, operands are hash references with one key/value pair: operand, when binary operators are simple scalars. So string x = 10 OR (x
20 AND x < 30)> is parsed into the following structure:
[
{ operand => 'x = 10' },
'OR',
[
{ operand => 'x > 20' },
'AND',
{ operand => 'x < 30' },
]
]
parse
Takes named arguments: string and callback. Where the first one is scalar with expression, the latter is a reference to hash with callbacks: open_paren, operator operand, close_paren and error. Callback for errors is optional and parser dies if it's omitted. Each callback is called when parser finds corresponding element in the string. In all cases the current match is passed as argument into the callback.
Here is simple example based on "as_array" method:
# result tree and the current group
my ($tree, $node);
$tree = $node = [];
# stack with nested groups, outer most in the bottom, inner on the top
my @pnodes = ();
my %callback;
# on open_paren put the current group on top of the stack,
# create new empty group and at the same time put it into
# the end of previous one
$callback{'open_paren'} = sub {
push @pnodes, $node;
push @{ $pnodes[-1] }, $node = []
};
# on close_paren just switch to previous group by taking it
# from the top of the stack
$callback{'close_paren'} = sub { $node = pop @pnodes };
# push binary operators as is and operands as hash references
$callback{'operator'} = sub { push @$node, $_[0] };
$callback{'operand'} = sub { push @$node, { operand => $_[0] } };
# run parser
$parser->parse( string => $string, callback => \%callback );
return $tree;
Using this method you can build other representations of an expression.
AUTHORS
Ruslan Zakirov <ruz@cpan.org>, Robert Spier <rspier@pobox.com>
COPYRIGHT
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.