Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Set modules and object comparison

by qq (Hermit)
on Sep 17, 2007 at 17:51 UTC ( #639454=perlquestion: print w/replies, xml ) Need Help??

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.


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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://639454]
Approved by Corion
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2022-01-20 06:21 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (56 votes). Check out past polls.