๐Ÿ“˜ Counting hash values in Perl 6

Having a hash, count the number of occurrences of each of its values.

For example, a hash is a collection mapping a carโ€™s license plate to the colour of the car or a passport number to the name of the street where the person lives. In the first example, the task is to count how many cars of each colour there are. In the second example, we have to say how many people live on each street. But letโ€™s simply count the colours of fruit ๐Ÿ™‚

my %data =
    apple => 'red',     avocado => 'green',
    banana => 'yellow', grapefruit => 'orange',
    grapes => 'green',  kiwi => 'green',
    lemon => 'yellow',  orange => 'orange',
    pear => 'green',    plum => 'purple',

By the way, notice that Perl 6 is tolerant of the comma after the last value in the hash initializer list.

Now it is time to count the statistics that we need.

my %stat;
%stat{$_}++ for %data.values;
say %stat;

Theย valuesmethod returns a list of all the values that the hash contains. In the loop, they increment the values of theย %stat hash. A new key is added toย %stat as soon as a new value fromย %data is seen. An increment of the newly-created element sets the corresponding value to 1. Print theย %stat hash and see the result. Notice that the output data is not ordered.

{green => 4, orange => 2, purple => 1, red => 1, yellow => 2}

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