in reply to Best way to compare two objects?

OK, here's what I came up with:

package Event; use Moose; use Modern::Perl; my $meta = __PACKAGE__->meta; use overload 'eq' => \&compare; sub compare { no strict 'refs'; my ($event1, $event2) = @_; for my $attr( $meta->get_all_attributes ) { #skip attributes that shouldn't be compared next if $attr eq 'post_id' || $attr eq 'status'; my $type = $attr->type_constraint->name; my $attr_name = $attr->name; if ($type eq 'Str') { return 0 if $event1->$attr_name ne $event2->$attr_name; } if ($type eq 'Int') { return 0 if $event1->$attr_name != $event2->$attr_name; } if ($type eq 'Time::Piece') { no warnings 'uninitialized'; logd('comparing times'); return 0 if $event1->$attr_name != $event2->$attr_name; } } return 1; }

Used like so:

my $event1 = Event->new({location => 'hell'}); my $event2 = Event->new({location => 'hell'}); if ($event1 eq $event2) { say 'equal!'; } else { say 'not equal!'; }

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re^2: Best way to compare two objects?
by Anonymous Monk on Mar 22, 2016 at 21:40 UTC

    I haven't tested it, but I'd be surprised if no strict 'refs'; really was necessary, and if it was, I'd try to find a way to code it with all strictures enabled. In any case, if it really is necessary to disable strictures, it should be done in as small a scope as possible.