Ovid has asked for the wisdom of the Perl Monks concerning the following question:
I've released a module named Array::AsHash which allows one to use references as hash keys (it actually does a lot more than this, but this is one of the features). Normally, this works fine:
my $array = Array::AsHash->new({array => \@array}); my $value = $array->get($some_reference);
It does this by checking the Scalar::Util::refaddr of the reference. However, this can fail if someone wants to override equality. In Python, you can get around this by overriding the __hash__() method of object. In Perl, we can't do this with unblessed references. Thus, the following will never succeed:
my $aref = [1,2,3]; my $array = Array::AsHash->new({ array => [ $aref => 'Ovid' ] }); print $array->get($aref); # prints "Ovid" print $array->get([1,2,3]); # fails
Ordinarily, this is fine. However, if we only care about the values a reference contains and not whether or not it's the same reference, we're stuck. I'd like to be able to pass the constructor a coderef which will determine equality of references beyond simply comparing their addresses. Things like the Test::More::is_deeply function or the useful Test::Deep module would be great, but they're tied to Perl's testing framework.
Can anyone offer suggestions?
For those wondering why I want to do this, I don't need this myself (yet), but I'm creating a flexible general purpose tool for folks and I'd like to give them the ability to override behavior as needed.
Cheers,
Ovid
New address of my CGI Course.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Using references as hash keys
by tye (Sage) on Oct 16, 2005 at 04:09 UTC | |
Re: Using references as hash keys
by geektron (Curate) on Oct 16, 2005 at 06:57 UTC | |
Re: Using references as hash keys
by xdg (Monsignor) on Oct 16, 2005 at 12:04 UTC | |
Re: Using references as hash keys
by traveler (Parson) on Oct 16, 2005 at 14:36 UTC | |
Re: Using references as hash keys
by adrianh (Chancellor) on Oct 16, 2005 at 17:51 UTC | |
by Tanktalus (Canon) on Oct 16, 2005 at 18:03 UTC | |
by adrianh (Chancellor) on Oct 16, 2005 at 21:50 UTC | |
by Tanktalus (Canon) on Oct 16, 2005 at 22:05 UTC | |
Re: Using references as hash keys
by Moron (Curate) on Oct 18, 2005 at 13:56 UTC | |
by Roy Johnson (Monsignor) on Oct 18, 2005 at 14:22 UTC |