如何为哈希创建代理对象?我似乎找不到传递哈希键的方法:
#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
是单个容器 aka Scalar
的替代品.一个 Hash
是复数容器,其中每个元素默认为 Scalar
.
一种可能的解决方案(基于 How to add subscripts to my custom Class in Perl 6? )是委托(delegate) Associative
的实现到内部散列但覆盖 AT-KEY
替换默认Scalar
的方法与 Proxy
:
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}
关于object - 哈希的代理对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58088825/