Count how many times a particular element appears in the array.
Letās have an array with a list of fruits; some of them are repeated.
my @data = < Ā Ā Ā Ā appleĀ Ā Ā Ā Ā Ā Ā pearĀ Ā Ā Ā Ā Ā grapeĀ Ā Ā Ā Ā lemon Ā Ā Ā Ā peachĀ Ā Ā Ā Ā Ā Ā appleĀ Ā Ā Ā Ā Ā bananaĀ Ā Ā grapeĀ Ā Ā Ā Ā pineappleĀ Ā avocado >;
Now, the task is to count how many times the elementĀ 'grape' appears there. First, extract all the elements to a temporary array by using theĀ grep method, and then call theĀ elems method to get the number of elements in the filtered data.
my $n = @data.grep('grape').elems;
say $n; # 2
Notice also a very handy way of defining arrays of strings. Instead of quoting all the elements, use theĀ <...> syntax to create a list out of space-separated values.Ā
If you need to determine the number of occurrences for more than one element, then it is better to use the more efficient technique to avoidĀ grepping the array for every item.
my %count;
%count{$_}++ for @data;
say %count<pineapple>;Ā # 1
say %count<grape>;Ā Ā Ā Ā Ā # 2