Perl6: Sorting Hash by Values and using kv
my %hash = :a<z>, :b<y>, :c<x>;
for %hash.sort(*.value) {
say $_.key;
say $_.value;
}
.kv
returns a flat sequence.
my %h = (
a => 3,
b => 2,
c => 1,
);
say %h.kv.perl;
# ("a", 3, "c", 1, "b", 2).Seq
If you sort it, then you do so without keeping the key with its associated value.
say %h.kv.sort.perl;
# (1, 2, 3, "a", "b", "c").Seq
So you want to sort it before splitting up the pairs.
# default sort order (key first, value second)
say %h.sort.perl;
# (:a(3), :b(2), :c(1)).Seq
say %h.sort: *.value; # sort by value only (tied values are in random order)
# (:c(1), :b(2), :a(3)).Seq
say %h.sort: *.invert; # sort by value first, key second
# (:c(1), :b(2), :a(3)).Seq
say %h.sort: *.kv.reverse; # sort by value first, key second
# (:c(1), :b(2), :a(3)).Seq
Once it is sorted you can take it as a sequence of Pair objects:
# default $_
for %h.sort: *.invert {
say .key ~ ' => ' ~ .value
}
# extract as named attributes
for %h.sort: *.invert -> (:$key, :$value) {
say "$key => $value"
}
# more explicit form of above
for %h.sort: *.invert -> Pair $ (:key($key), :value($value)) {
say "$key => $value"
}
Or you could pull apart the pairs after the sort:
(Notice the two-level structure.)
say %h.sort(*.invert).map(*.kv).perl;
# (("c", 1).Seq, ("b", 2).Seq, ("a", 3).Seq).Seq
say %h.sort(*.invert)».kv.perl;
# (("c", 1).Seq, ("b", 2).Seq, ("a", 3).Seq).Seq
# default $_
for %h.sort(*.invert).map(*.kv) {
say .key ~ ' => ' ~ .value
}
# extract inner positional parameters
for %h.sort(*.invert).map(*.kv) -> ($k,$v) {
say "$k => $v"
}
# `».kv` instead of `.map(*.kv)`
for %h.sort(*.invert)».kv -> ($k,$v) {
say "$k => $v"
}
You can even flatten it after pulling apart the pair objects.
say %h.sort(*.invert).map(*.kv).flat.perl;
# ("c", 1, "b", 2, "a", 3).Seq
say %h.sort(*.invert)».kv.flat.perl;
# ("c", 1, "b", 2, "a", 3).Seq
for %h.sort(*.invert).map(*.kv).flat -> $k, $v {
say "$k => $v"
}
for %h.sort(*.invert)».kv.flat -> $k, $v {
say "$k => $v"
}
(Note that ».method
only maps over one method call. To map over two you need ».method1».method2
, or just use map .map(*.method1.method2)
.
So in the ».kv.flat
above, only the .kv
method is mapped over the values.)