Badger::Logic

NAME

Top Close Open

Badger::Logic - parse and evaluate simple logical expressions

SYNOPSIS

Top Close Open
use Badger::Logic 'Logic';

my $logic  = Logic('animal and (eats_nuts or eats_berries)');
my $values = {
    animal    => 1,
    eats_nuts => 1,
}

if ($logic->test($values)) {
    print "This is an animal that eats nuts or berries\n";
}

DESCRIPTION

Top Close Open

This module implements a simple parser and evaluator for boolean logic expressions. It evolved from a piece of code that I originally wrote to handle role-based authentication in web applications.

EXPORTABLE SUBROUTINES

Top Close Open

LOGIC

Top Close Open

This is a shortcut alias to Badger::Logic.

use Badger::Logic 'LOGIC';

my $logic = LOGIC->new($expr);      # same as Badger::Logic->new($expr);

Logic()

Top Close Open

This subroutine returns the name of the Badger::Logic class when called without arguments. Thus it can be used as an alias for Badger::Logic as per LOGIC.

use Badger::Logic 'Logic';

my $logic = Logic->new($expr);      # same as Badger::Logic->new($expr);

When called with arguments, it creates a new Badger::Logic object.

my $logic = Logic($expr);           # same as Badger::Logic->new($expr);

METHODS

Top Close Open

new($expr)

Top Close Open

Constructor method to create a new Badger::Logic object from an expression.

my $logic = Badger::Logic->new('animal and (cat or dog)');

evaluate($values) / test($values)

Top Close Open

Method to evaluate the expression. A reference to a hash array should be passed containing the values that the expression can test.

my $values = {
    animal => 1,
    cat    => 1,
};

if ($logic->evaluate($values)) {
    print "This animal is a cat or a dog\n";
}

tree()

Top Close Open

Returns a reference to the root of a tree of Badger::Logic::Node objects that represent the parsed expression.

text()

Top Close Open

Returns a text representation of the logic expression.

INTERNAL METHODS

Top Close Open

parse($text)

Top Close Open

Main method to parse a logical expression. This calls parse_expr() and then checks that all of the text has been successfully parsed. It returns a reference to a Badger::Logic::Node object.

parse_expr($text)

Top Close Open

Method to parse a binary expression.

parse_unary($text)

Top Close Open

Method to parse a unary expression.

parse_term($text)

Top Close Open

Method to parse a single term in a logical expression.

AUTHOR

Top Close Open

Andy Wardley http://wardley.org

COPYRIGHT

Top Close Open

Copyright (C) 2007-2009 Andy Wardley. All Rights Reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Fork Me on Github