πŸ“˜ Sort hashes by parameter using Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s