Comparing objects for equality

  • Thread starter Jens Thoms Toerring
  • Start date
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top