in reply to Help on array element counting

Nothing too fancy, use map to replace for, just to demonstrate the use of map since this is your learning exercise. I also use the Data::Dumper module to investigate my data structure, which can be quite handy.
use Data::Dumper; @fruits = qw/ MANGO APPLE GRAPES MANGO MANGO MANGO MANGO APPLES APPLES BANANA CORN APPLES /; map { $count{$_}++ } @fruits; print Dumper(\%count);
And the output is -
$VAR1 = { 'GRAPES' => '1', 'CORN' => '1', 'APPLES' => '3', 'APPLE' => '1', 'BANANA' => '1', 'MANGO' => '5' };

Replies are listed 'Best First'.
Re: Re: Help on array element counting
by Hena (Friar) on Oct 28, 2003 at 07:44 UTC
    Also to illustrate point of 'sort' with hashes, I'd add to this a little. Sorting either by count
    @fruits = qw/ MANGO APPLE GRAPES MANGO MANGO MANGO MANGO APPLES APPLES BANANA CORN APPLES /; map { $count{$_}++ } @fruits; foreach (sort {$count{$a} <=> $count{$b}} keys %count) { print "$_ => $count{$_}\n"; }
    Or to sort them by fruits (changing the sort)
    foreach (sort {lc($a) cmp lc($b)} keys %count) { print "$_ => $count{$_}\n"; }