Comparing objects for equality

Discussion in 'Perl Misc' started by Jens Thoms Toerring, May 8, 2007.

  1. 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
    --
    \ Jens Thoms Toerring ___
    \__________________________ http://toerring.de
    Jens Thoms Toerring, May 8, 2007
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Smith

    comparing doubles for equality

    John Smith, Dec 30, 2006, in forum: C Programming
    Replies:
    12
    Views:
    719
  2. tom forsmo
    Replies:
    2
    Views:
    373
    Ian Wilson
    Apr 18, 2007
  3. Edward Rutherford

    Comparing fp types for equality

    Edward Rutherford, Dec 20, 2011, in forum: C Programming
    Replies:
    12
    Views:
    418
    Rui Maciel
    Dec 20, 2011
  4. Edgardo Hames

    Comparing two files for equality

    Edgardo Hames, Jan 12, 2005, in forum: Ruby
    Replies:
    11
    Views:
    466
    Martin DeMello
    Jan 18, 2005
  5. Shao Miller

    Pointer Equality for Different Array Objects

    Shao Miller, Feb 3, 2012, in forum: C Programming
    Replies:
    11
    Views:
    403
    Shao Miller
    Feb 6, 2012
Loading...

Share This Page