Badger::Logic(3pm)

NAME
Badger::Logic - parse and evaluate simple logical expressions

SYNOPSIS
    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
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

  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

  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.

  text()
Returns a text representation of the logic expression.

INTERNAL METHODS

  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
Andy Wardley <http://wardley.org>

COPYRIGHT
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.