๐Ÿ“˜ Sort hashes by parameter using Perl 6

๐Ÿ“˜ Sort hashes by parameter using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Sort a list of hashes using data in their values.

This task is commonly performed to sort items where the sortable parameter is one of the values in the hash, for example, sorting a list of people by age.

my @people = (
    {
        name => 'Kevin', age => 20,
    },
    . . .
    {
        name => 'Amanda', age => 19,
    },
);

@people.sort({
    %^a<age> <=> %^b<age>
}).say;

Theย sort method uses an optional code block that customises the sorting procedure. It takes two arguments, compares them, and returns the result of the comparison.

In the example shown,ย %^a andย %^b are the two placeholder variables created by the compiler. They alphabetically correspond to the first and the second arguments that the block receives.

Alternatively, it is possible to list the arguments in a pointy block explicitly:

@people.sort( -> %first, %second {
ย ย ย ย %first<age> <=> %second<age>
}).say;

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code