The idea is to loop through the original array. For each element, either look up or add that element as a key into a hash, and increments that key's value by one. Since Perl's hashes use autovivification, when we try to look up a non-existing key in a hash, that key will be added.
is a very common Perl idiom. If we are processing the element 'APPLE' and it is not in the hash, a new key will be added to the hash, and that key's value (currently undef) will be incremented by 1 ... yielding 1. Later, if we encounter 'APPLE' again, when we try to look up 'APPLE' it exists this time and the value returned is 1. Add 1 to that and now we have 2 apples. Remember, Data::Dumper is your friend! Try this out:$hash{$_}++ for @array;
use strict; use warnings; use Data::Dumper; my @fruit = qw( MANGO APPLE GRAPES MANGO MANGO MANGO MANGO APPLES APPLES BANANA CORN APPLES ); my %fruit; $fruit{$_}++ for @fruit; print Dumper \@fruit; print Dumper \%fruit;
jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
In reply to 3Re: Help on array element counting
by jeffa
in thread Help on array element counting
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |