sort 方法返回 List 的 Pairs。
由于在列表上调用.kv 会返回一个index, Pair 列表列表,这是您不想要的;你不能只打电话给.kv。因此,您必须通过在每个对象上调用.kv 方法,从列表中的Pair 对象中单独提取键和值,>>.kv 会这样做。
您也可以改用.map(*.kv)。
>>.kv 语法允许实现将工作分散到多个线程上,如果这样做有意义的话。
(目前 Rakudo 只是以半随机的顺序完成这项工作,以防止人们错误地使用该功能)
还有另一种编写循环的方法,即在子签名中使用副词提取属性:
for %hash.sort -> (:$key, :$value) {
say "'$key' => '$value'";
}
for %hash.sort -> $pair (:$key, :$value) {
say $pair;
say $key === $pair.key and $value === $pair.value; # True
}
# :$key is short for :key($key)
for %hash.sort -> (:key($k), :value($v)) {
say "'$k' => '$v'";
}
这对于其他没有创建公共属性列表的方法的对象很有用
class C { has $.a; has $.b; has $.c; has $!private-value }
my $c = 5;
my $obj = C.new(:a<A>,:b(1),:$c);
given $obj -> ( :$a, :b($b), :$c) ) {
say "$a $b $c";
}
# ignore $.a by using an unnamed scalar
given $obj -> ( :a($), :$b, :$c ) { ... }
# places any unspecified public attributes in %others
given $obj -> ( :$a, :$b, *%others ) {
.say for keys %others; # c
}
# ignores any unspecified attributes
# useful to allow subclasses to add more attributes
# or to just drop any values you don't care about
given $obj -> ( :$a, :$b, *% ) { ... }
# fails because it doesn't handle the public c attribute
# in the sub-signature
given $obj -> ( :$a, :$b ) { ... }
这只是签名的开始。
以下所有内容在子例程和方法签名中也是允许的,可选的,对于这个例子来说完全是多余的。
它在限制可能的候选者的多子和多方法中非常有用。
for 'one' => 1, 1/3
->
# Type is an alias to the object type
::Type Any $_ # Any is the default type requirement
# the public attributes of the object
(
::A-Type Any :key( :numerator( $a ) ),
::B-Type Any :value( :denominator( $b ) ) where $b >= 1,
)
{
my Type $obj = $_; # new variable declared as having the same type
my A-Type $new-a = $a;
my B-Type $new-b = $b;
# could have used $_.^name or .^name instead of Type.^name
# so you don't actually have to add the alias to the signature
# to get the name of the arguments type
say Type.^name, ' ', $_;
say ' ', A-Type.^name, ' ', $a;
say ' ', B-Type.^name, ' ', $b;
}
Pair one => 1
Str one
Int 1
Rat 0.333333
Int 1
Int 3
至于使用.sort({.key}),是的,这基本上是一样的,因为sort在那里接受任何Callable。
我想指出,您甚至不需要向 sort 提供参数,因为它的默认设置比您提供的更智能。
Perl 6 有多种创建和访问Callable 事物的方法。因此,以下任何一项都可以:
*.key
{ .key } # { $_.key }
-> $_ { .key } # basically what the previous line turns into
{ $^placeholder-var.key }
sub ($_) { .key }
&a-subroutine-reference # you would have to create the subroutine though
此外,由于所有普通运算符实际上都是子例程,因此您可以在需要Callable 的其他地方使用它们。 (不过我想不出一个能在那个地方工作的人)
&infix:<+> # the subroutines responsible for the numeric addition operator
&[+] # ditto
&prefix:<++>
&postfix:<++>
# etc