package Your::Comparable::Object;
use base 'Badger::Comparable';
# You must define a compare method that returns -1, 0 or +1
# if the object is less than, equal to, or greater than the
# object passed as an argument.
sub compare {
my ($this, $that) = @_;
# for example: comparing by a surname field
return $this->surname
cmp $that->surname;
}
package main;
# assume $obj1 and $obj2 are instance of above object class
if ($obj1 < $obj2) {
# do something
}
This module implements a base class for comparable objects. Subclasses need only define a compare() method and can inherit all the other methods provided. Overloaded comparison operators are also defined.
This method must be defined by subclasses. It received the implicit
$self object reference as the first argument and the object
it is being compared to as the second.
The method can do whatever is necessary to compare the two objects. It
should return -1 if the $self object should be
ordered before the $that object, +1 if
it should be ordered after, or 0 if the two objects are considered
the same.
This is mapped to the not_equal() method.
if ($obja != $objb) {
# do something
}
This is mapped to the not_after() method.
if ($obja <= $objb) {
# do something
}
This is mapped to the not_before() method.
if ($obja >= $objb) {
# do something
}
Andy Wardley http://wardley.org