哈希的代理对象?

Proxy object for a hash?

如何为哈希创建代理对象?我似乎找不到传递哈希键的方法:

1
2
3
4
5
6
7
8
9
10
11
12
#sub attr() is rw {
sub attr($name) is rw {
  my %hash;
  Proxy.new(
    FETCH => method (Str $name) { %hash?$name? },
    STORE => method (Str $name, $value) { %hash?$name? = $value }
  );
}

my $attr := attr();
$attr.bar = 'baz';
say $attr.bar;

Proxy 是单个容器又名 Scalar 的替代品。 Hash 是复数容器,其中每个元素默认为 Scalar.

一个可能的解决方案(基于 How to add subscripts to my custom Class in Perl 6?)是将 Associative 的实现委托给内部散列,但覆盖 AT-KEY 方法以将默认 Scalar 替换为Proxy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ProxyHash does Associative {

  has %!hash handles
    <EXISTS-KEY DELETE-KEY push iterator list kv keys values gist Str>;

  multi method AT-KEY ($key) is rw {
    my $element := %!hash{$key};
    Proxy.new:
      FETCH => method ()       { $element },
      STORE => method ($value) { $element = $value }
  }
}

my %hash is ProxyHash;
%hash<foo> = 42;
say %hash; # {foo => 42}