in reply to Re: Re: Help on array element counting
in thread Help on array element counting

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.

$hash{$_}++ for @array;
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:
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)