Badger::Logic - parse and evaluate simple logical expressions


Badger documentation  | view source Contained in the Badger distribution.

Index


NAME

Top

Badger::Logic - parse and evaluate simple logical expressions

SYNOPSIS

Top

    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

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

LOGIC

This is a shortcut alias to Badger::Logic.

    use Badger::Logic 'LOGIC';

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

Logic()

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

new($expr)

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)

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()

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

INTERNAL METHODS

Top

parse($text)

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)

Method to parse a binary expression.

parse_unary($text)

Method to parse a unary expression.

parse_term($text)

Method to parse a single term in a logical expression.

AUTHOR

Top

Andy Wardley http://wardley.org

COPYRIGHT

Top


Badger documentation  | view source Contained in the Badger distribution.