对哈希kv对进行排序
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语法允许实现在多个线程上传播工作,如果这样做有意义的话. 通过使用子签名中的副词提取属性,可以使用另一种方法编写循环: 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 至于使用 我想指出你甚至不需要为 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
