J
Jens Thoms Toerring
Hi,
I have often to compare objects for equality that are created
for an entry in a database, where equality means that the objects
refer to the same entry in the database. The normal '==' operator
of course only tells me if the objects are identical in the sense
that their addresses are the same, so it won't work for objects
created for the same database entry. But this is nearly never what
I'm really interested in so I usually overload the '==' (and '!=')
operator to do something like
use overload '==' => sub { die 'Invalid comparison'
unless $_[ 0 ]->isa( __PACKAGE__ ) and
$_[ 1 ]->isa( __PACKAGE__ );
$_[ 0 ]->id == $_[ 1 ]->id },
'!=' => sub { die 'Invalid comparison'
unless $_[ 0 ]->isa( __PACKAGE__ ) and
$_[ 1 ]->isa( __PACKAGE__ );
$_[ 0 ]->id != $_[ 1 ]->id },
fallback => 1;
with '$object->id' being the method to determine the primary key
of the entry in the database for '$object' (it gets more inter-
esting if there isn't a simple primary key). While this works
quite fine so far I am wondering if there is some better, more
elegant (and maybe even faster;-) method to do such a comparison
for (in-) equality
Regards, Jens
I have often to compare objects for equality that are created
for an entry in a database, where equality means that the objects
refer to the same entry in the database. The normal '==' operator
of course only tells me if the objects are identical in the sense
that their addresses are the same, so it won't work for objects
created for the same database entry. But this is nearly never what
I'm really interested in so I usually overload the '==' (and '!=')
operator to do something like
use overload '==' => sub { die 'Invalid comparison'
unless $_[ 0 ]->isa( __PACKAGE__ ) and
$_[ 1 ]->isa( __PACKAGE__ );
$_[ 0 ]->id == $_[ 1 ]->id },
'!=' => sub { die 'Invalid comparison'
unless $_[ 0 ]->isa( __PACKAGE__ ) and
$_[ 1 ]->isa( __PACKAGE__ );
$_[ 0 ]->id != $_[ 1 ]->id },
fallback => 1;
with '$object->id' being the method to determine the primary key
of the entry in the database for '$object' (it gets more inter-
esting if there isn't a simple primary key). While this works
quite fine so far I am wondering if there is some better, more
elegant (and maybe even faster;-) method to do such a comparison
for (in-) equality
Regards, Jens