pme and karlgoethebier have both given great answers on how to solve this problem.
pme uses a hash to get the count. As you go through each element in @array, a hash key/value pair is either created or updated. If the key does not exist, for example, the first time dog is come across in @array, a key is created in %hash. The value is incremented to 1. The same applies to the first time for cat and sheep. The second and third times an item is come across, the key already exists, so the key is not created again, but the value is incremented.
karlgoethebier goes through the array and uses the g modifier in the regex to substitute all the occurrences of each element with nothing while at the same time capturing the number of times the substitution was made. The s substitution operator will return the number of substitutions made when used with g.
Looking at your code, I do get values other than 1. I get
dog, dog, 1 dog, dog, 2 dog, dog, 3 cat, cat, 1 cat, cat, 2 sheep, sheep, 1 dog, dog, 1 dog, dog, 2 dog, dog, 3 dog, dog, 1 dog, dog, 2 dog, dog, 3 cat, cat, 1 cat, cat, 2
It appears that what you are really processing is a file with lines that start with date/time stamps, but that is really immaterial. What you are doing is going through the data loop once for the first item ($i = 'dog'), then again through the whole loop when $i = 'cat', and so on, up to the last cat.
The first time through, $i and $j will both match on the first dog, so $cnt is 1, then again on the second dog, so $cnt is 2, then again on the third dog, so $cnt is three. That is all on the first loop with $i = 'dog'.
On the next loop, $i becomes 'cat' and $cnt is set back to zero. On the first cat (the second item), $i and $j are equal, so $cnt is bumped up to one. On the second cat (the last item), it is bumped up to 2.
$i takes on sheep, dog, dog, and cat for the following outer loops. We get the rest of the printout above. You could determine what the number of each animal is by looking at your printout, but you probably didn't want it in the form you have. You have it set to print each time your $i and $j are equal, so it will show the count in progress each time it goes through the $j loop. What you really wanted was the grand total at the end. For that, you would better be served by pme or karlgoethebier solutions.
NOTE: I changed qw('dog', 'cat', 'sheep', 'dog', 'dog', 'cat') to qw( dog cat sheep dog dog cat) since qw is rather adept at making a list out of just words. Adding the single quotes and commas will just confuse things and put extra quotes and commas in the list and make the first cat not match the second.
In reply to Re: How do I count the number of occurrences of each string in an array?
by ExReg
in thread How do I count the number of occurrences of each string in an array?
by aschwa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |