Pathologically Eclectic Rubbish Lister PerlMonks

### [Perl6] Sort a hash by value

by haoess (Curate)
 on Dec 09, 2008 at 19:01 UTC ( #729238=perlquestion: print w/ replies, xml ) Need Help??
haoess has asked for the wisdom of the Perl Monks concerning the following question:

Like in Perl 5 you can print your hash sorted by its values:

```my %nums = (
four  => 4,
one   => 1,
three => 3,
two   => 2,
);

for %nums.keys.sort: { %nums{\$^a} <=> %nums{\$^b} } -> \$key {
say "\$key {%nums{\$key}}";
}
Output (it works with my latest Rakudo checkout):
```one 1
two 2
three 3
four 4

Maybe there's a more comfortable (aka shorter) way to get this, without writing %nums three times on the same line?

Thanks, Frank

Replies are listed 'Best First'.
Re: [Perl6] Sort a hash by value
by moritz (Cardinal) on Dec 09, 2008 at 19:13 UTC
```my %nums = (
four  => 4,
one   => 1,
three => 3,
two   => 2,
);

for %nums.pairs.sort: { \$^a.value <=> \$^b.value } -> \$pair {
say \$pair;
}

(not necessarily shorter, but mentions %nums only once in the sort line).

There was also a proposal to make the sort method accept a block of arity one that automatically performs a ST, but it doesn't seem to be in the spec, and thusly isn't implemented by Rakudo right now.

Update: clinton asked in the CB what the colon after the sort was about, so here's the explanation for everybody: The are two syntax forms for method calls in Perl 6, \$object.method(\$arg1, \$arg2, ...) and \$object.method: \$arg1, \$args, .... My example uses the latter to avoid more parenthesis.

There was also a proposal to make the sort method accept a block of arity one that automatically performs a ST, but it doesn't seem to be in the spec, and thusly isn't implemented by Rakudo right now.

Thanks to pmichaud++, now it is (he says).

Update: Here's his blog entry.

-- Frank

Create A New User
Node Status?
node history
Node Type: perlquestion [id://729238]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2016-07-29 12:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What is your favorite alternate name for a (specific) keyboard key?

Results (261 votes). Check out past polls.