in reply to Objects as hash keys?

package MyObj; sub new { bless {}, shift; } 1; --- #!/usr/bin/perl -w use MyObj; my %hash; my $a = MyObj->new(); my $b = MyObj->new(); $hash{$a} = "This is my Object A"; $hash{$b} = "This is my Object B"; print $a, "\n"; print $b, "\n"; print $_, " : ", $hash{$_}, "\n" foreach keys %hash; __END__ MyObj=HASH(0x2001b1fc) MyObj=HASH(0x2001b2e0) MyObj=HASH(0x2001b1fc) : This is my Object A MyObj=HASH(0x2001b2e0) : This is my Object B
Looks like it can be done...

Replies are listed 'Best First'.
Re^2: Objects as hash keys?
by ikegami (Patriarch) on May 17, 2005 at 16:59 UTC

    One caveat:

    package MyObj; sub new { bless {}, shift; } sub test { print("test\n"); } package main; my $o = MyObj->new(); my %hash; $hash{$o} = "This is my object"; foreach (keys(%hash)) { print("$_\n"); # MyObj=HASH(0x1abefc0) print("$hash{$_}\n"); # This is my object $_->test(); # Can't locate object method "test" via package # "MyObj=HASH(0x1abefc0)" (perhaps you forgot to # load "MyObj=HASH(0x1abefc0)"?) at script.pl line 26 }
      Exactly my point.
      --Artist