http://qs321.pair.com?node_id=639454

qq has asked for the wisdom of the Perl Monks concerning the following question:

I've got an easy Set problem. I have two lists of objects and I want intersection and difference, etc.

BUT I'd like to have them be compared by calling $_->id rather than refaddr $_. I don't think either Set::Object or Set::Scalar allow the user to provide an identity comparison function, or make clear how to subclass to change identity comparison.

Am I missing it, or is there another module that allows this? It seems like a common need.

thanks

update: edited for clarity

Replies are listed 'Best First'.
Re: Set modules and object comparison
by Joost (Canon) on Sep 17, 2007 at 19:26 UTC
Re: Set modules and object comparison
by kyle (Abbot) on Sep 17, 2007 at 18:35 UTC

    I don't know of another module that allows this. My suggestion would be to take the source of one of those, pull out the algorithms you want, and modify them to your need.

    In the case of Set::Scalar, it looks as if all you'd have to change is Set::Scalar::Base::_strval (but I haven't tried it, of course).

    I'm actually surprised to find that they use refaddr explicitly. I was hoping to find that you could get the behavior you want by overloading either stringification or equivalence, but that's not what I found.

Re: Set modules and object comparison
by suaveant (Parson) on Sep 17, 2007 at 19:19 UTC
    Should be relatively easy to code yourself...
    sub object_set { my($lista,$listb) = @_; my(%seen,%seen2); for(@$lista) { push @{$seen{$_->id}}, $_; } for(@$listb) { if($seen{$_->id}) { push @{$seen2{$_->id}}, @{delete($seen{$_->id})}, $_; } elsif($seen2{$_->id}) { push @{$seen2{$_->id}}, $_; } else { push @{$seen{$_->id}}, $_; } } return { diff => \%seen, int => \%seen2 }; }
    Not tested, but the idea is there and easily tweaked. Since you don't want to use refaddrs I assume you can have multiple references that have the same id, so I pushed them onto an array to catch them all. Hope that helps.

                    - Ant
                    - Some of my best work - (1 2 3)

Re: Set modules and object comparison
by qq (Hermit) on Sep 18, 2007 at 11:30 UTC

    Thanks for the helpful replies. I'll let you know what I end up with.