在探索最近在这里提到的
perl6 question中提出的文档示例时,我发现最终的实现选项 – (我对该示例的解释是它提供了三种不同的方法来做某事) – 不起作用.跑这个;
class HTTP::Header does Associative {
has %!fields handles <iterator list kv keys values>;
sub normalize-key ($key) { $key.subst(/\w+/, *.tc, :g) }
method EXISTS-KEY ($key) { %!fields{normalize-key $key}:exists }
method DELETE-KEY ($key) { %!fields{normalize-key $key}:delete }
method push (*@_) { %!fields.push: @_ }
multi method AT-KEY (::?CLASS:D: $key) is rw {
my $element := %!fields{normalize-key $key};
Proxy.new(
FETCH => method () { $element },
STORE => method ($value) {
$element = do given $value».split(/',' \s+/).flat {
when 1 { .[0] } # a single value is stored as a string
default { .Array } # multiple values are stored as an array
}
}
);
}
}
my $header = HTTP::Header.new;
say $header.WHAT; #-> (Header)
$header<Accept> = "text/plain";
$header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;
$header.push('Accept-Language' => "fr"); # like .push on a Hash
say $header<Accept-Language>.perl; #-> $["en", "fr"]
…产生预期的输出.请注意,带有X元运算符的第三行最后一行将一个文字列表(使用尖括号构建)分配给一个哈希切片(给定一个灵活的“哈希”定义).我的理解是这导致对方法AT-KEY的三次单独调用,每次调用一个字符串参数(除了self),因此不会执行给定语句的默认子句.那是对的吗?
当我发明一个超出代码部分的用例时,它似乎失败了;
... as above ...
$header<Accept> = "text/plain";
$header{'Accept-' X~ <Charset Encoding Language>} = <utf-8 gzip en>;
$header{'Accept-Language'} = "en, fr, cz";
say $header<Accept-Language>.perl; #-> ["en", "fr", "cz"] ??
# outputs
(Header)
This Seq has already been iterated, and its values consumed
(you might solve this by adding .cache on usages of the Seq, or
by assigning the Seq into an array)
in block at ./hhorig.pl line 20
in method <anon> at ./hhorig.pl line 18
in block <unit> at ./hhorig.pl line 32
错误消息提供了一个很棒的解释 – 主题是由拆分生成的序列,现在已经花费,因此无法在when和/或default子句中引用.
我是否正确“解除”并实施了这个例子?我发明的一个字符串中的几个语言代码的用例是错误的还是示例代码错误/过时了?我说过时了,因为我的回忆是Seq在perl6开发过程中很晚才出现 – 所以也许,这段代码曾经工作但现在还没有.任何人都可以澄清/确认吗?
最后,考虑到错误消息,以下代码似乎可以解决问题;
... as above ...
STORE => method ($value) {
my @values = $value».split(/',' \s+/) ;
$element = do given @values.flat {
when 1 { $value } # a single value is stored as a string
default { @values } # multiple values are stored as an array
}
}
……但它是否完全相同?
最佳答案 该代码现在可以使用(Rakudo 2018.04)并打印
$["en", "fr", "cz"]
如预期.这可能是一个最终解决的错误.