If I structure a solution as a c, java, or BASIC programmer might:
my %word_list = ( bat=> 0, cat=> 0, eat=> 0, fat=> 0 );
my @words = qw( bat bat dat fat eat eat eat fat );
my $word;
foreach $word (@words){
if(exists $word_list{$word}){
$word_list{$word}= $word_list{$word} + 1;
}
else{
$word_list{$word} = 1;
}
}
foreach $word (sort keys %word_list) {
print "$word: $word_list{$word}\n";
}
If I want a perlish solution I would write:
%word_list = ( bat=> 0, cat=> 0, eat=> 0, fat=> 0 );
my @words = qw( bat bat dat fat eat eat eat fat );
my $word;
foreach $word (@words){
$word_list{$word}++;
}
foreach $word (sort keys %word_list) {
print "$word: $word_list{$word}\n";
}
If don't need a the original word_list for displaying words that were not matched (word count is 0) but want only the counts of the words that occur in @words then an empty %word_list.
my %word_List = ( );
Using a hash and increment to count things is a fundamental technique to master early in your perl walk.
RBL |