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; |
一个可能的解决方案(基于 How to add subscripts to my custom Class in Perl 6?)是将
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} |