perl: count unique elements in array

arrays, counting, perl

Solution

Use a hash to count the number of times each name occurs:

use warnings;
use strict;
use Data::Dumper;
$Data::Dumper::Sortkeys=1;

my @names = qw(bob mike joe bob);
my %counts;
$counts{$_}++ for @names;
print Dumper(\%counts);

__END__

$VAR1 = {
          'bob' => 2,
          'joe' => 1,
          'mike' => 1
        };

Problem

I have a simple array with names in it, and I want to be able to easily print out the number of times each name appears. I have tried making a ton of for loops an diff statements to first make another array with unique values then, trying to count the values in the orinal array and store them in a 3rd array. This seemed overly complex, and i wanted to see if maybe there was a much simpler way to do this.

Original source