Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object as hash key

Tags:

hash

perl

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;
}
like image 549
Trevor Avatar asked Aug 13 '10 18:08

Trevor


People also ask

Can an object be a key in JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.

Is a hash an object?

One of the most important differences between Ruby and JavaScript is in how they handle the composite data structures. Ruby does this with the hash, while JS calls its version an object. Ruby's hash and JavaScript's object do roughly the same thing—they both represent a collection of values accessed using keys.

What is the HashKey?

HashKey is a unique one-key keyboard dedicated solely to the awesome hashtag. No more wondering how to do a hashtag on your computer or having to press two keys to make it happen!


Video Answer


1 Answers

By default, all hash keys in Perl are strings, so what is happening in you code (which has other problems as well), is you are converting the object to a string and storing the string.

In general, if you want to use a object as a key, the simplest way to do it is to use two data structures, one that holds your objects (an array), and another that maps the objects to some values (a hash). It is also possible to create a tied hash which will support objects as keys, but in general, tied hashes are going to be slower than simply using two data structures.

The standard module Tie::RefHash provides a mechanism for using objects (and other references) as hash keys (that work properly when you get them back).

use Tie::RefHash;
tie my %hash, 'Tie::RefHash';

$hash{MyClass->new(1)} = 0;  # never use the indirect object syntax
....
like image 127
Eric Strom Avatar answered Oct 18 '22 15:10

Eric Strom