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.
use List::MoreUtils qw(uniq);
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.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With