问题描述
$ perl6 -e'use Test;我们正在寻找解释为什么这两个数据结构不相等: is-deeply [{a => b}],[{a => 'b'},];'
not ok 1 -
#在-e行1
#期望的失败测试:$ [{:a(b)},]
$ got:$ [:a(b)]
Hashes和Arrays中的尾随逗号是无意义的,就像在P5中:
$ perl6 -e'[1] .elems.say; [1,] .elems.say'
1
1
但没有它散布在某种程度上丢失了,并且变成了对数组:
$ perl6 -e'[{a => b,c => d}] .elems.say;'
2
重构法适用于此,但我希望得到更详细的解释,以理解背后的逻辑。
Hashes和Arrays中的尾随逗号与P5中一样没有意义
不,这并不意味着什么:
(1).WHAT.say; #(Int)
(1,)。WHATsay; #(列表)
List Refactor切换到以迭代特征. That is to say, features like a for or the array and hash composers (and subscripts) always get a single argument. That is indeed what's going on with your original example.
The single argument may be -- often will be -- a list of values, possibly even a list of lists etc., but the top level list would still then be a single argument to the iterating feature.
If the single argument to an iterating feature does the Iterable role (for example lists, arrays, and hashes), then it's iterated. (This is an imprecise formulation; see my answer to "When does for call the iterator method?" for a more precise one.)
So the key thing to note here about that extra comma is that if the single argument does not do the Iterable role, such as 1, then the end result is exactly the same as if the argument were instead a list containing just that one value (i.e. 1,):
.perl.say for {:a("b")} ; # :a("b") Iterable Hash was iterated .perl.say for {:a("b")} , ; # {:a("b")} Iterable List was iterated .perl.say for 1 ; # 1 Non Iterable 1 left as is .perl.say for 1 , ; # 1 Iterable List was iterated
The typical way "to preserve structure [other than] using trailing comma when single element list is declared" (see comment below), i.e. to stop a single Iterable value being iterated as it normally would, is by item-izing it with a $:
my @t = [ $[ $[ "a" ] ] ]; @t.push: "b"; @t.perl.say; # [[["a"],], "b"]
The iteration is used to get values to be passed to some code in the case of a for; to get values to become elements of the array/hash being constructed in the case of a composer; to get an indexing slice in the case of a subscript; and so on for other iterating features.
这篇关于意外的哈希展平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!