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]
[/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]
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.