Is it possible to use an object as a hash key?
For example, the following code allows me to use an instance of MyClass as a key but when I iterate over the keys and attempt to invoke the get_value
method, I get the error:
Can't locate object method "get_value" via package "MyClass=HASH(0x12a4040)" (perhaps you forgot to load "MyClass=HASH(0x12a4040)"?)
package MyClass;
use strict;
sub new
{
my $class = shift;
my $self = {
_value => shift
};
bless $self, $class;
return $self;
}
sub get_value {
my($self) = @_;
return $self->{_value};
}
my %hash = ();
%hash->{new MyClass(1)} = 0;
%hash->{new MyClass(2)} = 1;
for my $key (keys %hash)
{
print $key->get_value;
}
TO_JSON
method if it matters to that object. Unrelated to that, you are making a shallow copy in thatTO_JSON
, which is probably not what you want. – Snorter