Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I count the unique elements of an array?

Little tricks

How do I count the unique elements of an array?

by  stillflame  Posted    (Edited  )
Hashes automatically prevent you from having two
different keys with the same name. If you assign different
values to the same element, the second one just rewrites
the first. Thus, if you map an array onto the keys of a
hash with a value of one more than it's current value, you
get back a hash of elements corresponding to the unique
elements of an array and values equal to the number of
occurances of each.
[tt][color blue]
sub count_unique {
my @array = @_;
my %count;
map { $count{$_}++ } @array;

[/color][color purple] #print them out:[/color][color blue]

map {print "$_ = ${count{$_}}\n"} sort keys(%count);

[/color][color purple] #or just return the hash:[/color][color blue]

return %count;
}
[/tt][/color]

Alternatively, you could want to just get back an array of
the unique elements, not being concerned with the number of
occurances.
[tt][color blue]
sub return_unique {
my @array = @_;
my %count;
map {$count{$_} = 1} @array;
return sort keys(%count);
}
[/tt][/color]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top