Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: count unique elements in array

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.

like image 951
Ten Digit Grid Avatar asked Apr 17 '12 15:04

Ten Digit Grid


People also ask

How do I find unique elements in an array in Perl?

use List::MoreUtils qw(uniq);

How do I sort unique values in Perl?

uniq() takes a list of elements and returns the unique elements of the list. Each element may be a scalar value or a reference to a list. If set to a true value, the unique elements of the list will be returned sorted. Perl's default sort will be used unless the compare option is also passed.


1 Answers

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
        };
like image 160
toolic Avatar answered Oct 13 '22 10:10

toolic