Wednesday, September 19, 2007

Occurence of each value in a list.

Usual approach is
@list=(1,2,3,4,5,4,3,2,1,2,3,4,5,4,3,2,1);
for (@list) {
$count++ if $_ eq "3";
}
We can smarten this by using grep function.
$count = grep $_ eq "3", @list;
But when we need the number of 4 or 5, we must repeat the above again.
This can be made easy by hash in a single line as,
my %count;
$count{$_}++ for @list;
foreach $key (keys %count){
print $key."\t".$count{$key}."\n";
}

No comments: