如何为哈希创建代理对象?我似乎找不到传递哈希键的方法:
#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;
A Proxy
代替了单个容器Scalar
。 Scalar
是多个容器,其中每个元素默认都是Hash
。
一种可能的解决方案(基于Scalar
)是将How to add subscripts to my custom Class in Perl 6?的实现委派给内部哈希,但重写Associative
方法以将默认的AT-KEY
替换为Scalar
:
Proxy