my %hash = two => 2,three => 3,one => 1,; for %hash.sort(*.key)>>.kv -> ($key,$value) { say "'$key' => '$value'"; }
%hash.sort({.key})>> .kv是否相当于以上排序?
为什么没有超级>>这种方法不起作用暗示?
解决方法
sort
方法返回0700的
Pairs.
由于在列表上调用.kv
会返回一个您不想要的索引列表,即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,*%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,*% ) { ... } # 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