How to count duplicates in a hash in perl -


please bear me.

write program reads series of words (with 1 word per line)1 until end-of-input, print summary of how many times each word seen. (hint: remember when undefined value used if number, perl automatically converts 0. may @ earlier exercise kept running total.) if input words fred, barney, fred, dino, wilma, fred (all on separate lines), output should tell fred seen 3 times. credit, sort summary words in ascii order in output.

[1] has 1 word per line because still haven't shown how extract individual words line of input.

this 1 should use hash. , can't figure out how. can think of using array , using 2 loops compare duplicates. guess didn't understand problem right. here's code using array.

#! usr/bin/perl use warnings; use strict;  chomp(my @input = <stdin>);  foreach $name (@input) {     $count;      foreach $compare_name (@input) {         if ($name eq $compare_name) {             $count += 1;         }     }      print "$name seen $count times\n"; } 

but prints example:

myname myname myname  prints: myname seen 3 times myname seen 3 times myname seen 3 times 

can guide me on how use hash on one? thanks

it 3 times, because have 3 iterations of outer loop, each yielding same results (3 times).

a simple way is:

my %occurs; while (<stdin>)  {     chomp($_);     $occurs{$_}++; }  foreach $occur (sort keys %occurs) {     print "$occur seen $occurs{$occur} times\n"; } 

Comments