Skip to content

Instantly share code, notes, and snippets.

@jnthn
Forked from moritz/objhash.pl
Created February 14, 2012 13:31
Show Gist options
  • Save jnthn/1826773 to your computer and use it in GitHub Desktop.
Save jnthn/1826773 to your computer and use it in GitHub Desktop.
First experiments with
class ObjHash {
has %!keys handles (keys => 'values');
has %!values handles <values elems>;
method at_key(Mu $key) is rw {
my $lkey = $key.WHICH;
%!values.exists($lkey)
?? %!values{$lkey}
!! pir::setattribute__0PPsP(my $v, Scalar, '$!whence',
-> {
%!keys{$lkey} := $key;
%!values{$lkey} := $v ;
}
);
}
method bind_key(Mu $key, \$value) {
my $lkey = $key.WHICH;
%!keys{$lkey} = $key;
%!values{$lkey} := $value;
}
method pairs() {
%!keys.keys.map({; %!keys{$_} => %!values{$_}});
}
method kv() {
%!keys.keys.map({; %!keys{$_}, %!values{$_}});
}
}
# works:
my $x = ObjHash.new;
my $a = (class A { }).new;
$x{$a} := 'foo';
say $x{$a};
say $x.keys.[0] === $a;
$x{'foo'} = 'blub';
say $x{'foo'};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment