while ($word = <STDIN>) {
$length = length($word) -1; # Subtract 1 for included newline char
$wordLength[$length]++;
}
print "Word length \t\t Occurrences \n\n";
for ( my $i =1; $i <= $#wordLength; $i++ ) {
if (not exists $wordLength[$i]) {
print "$i \t\t\t 0 \n";
}
else {
print "$i \t\t\t $wordLength[$i] \n";
}
}
This works great reading in a txt file and outputting as such:
Word Length Occurrence
1 27
2 104
3 1039
4 3505
5 7181
6 11765
7 15898
I am trying to get this to work using hash instead of an array but it doesn't seem to work. This is my attempt:
while ($word = <STDIN>) {
chomp($word);
$length = length($word);
$wordLength{$word} = "$length";
}
foreach $word (sort keys %wordLength) {
print "$word, $wordLength{$word}\n"; # print key and value
}
$wordLength{$length}? It's super odd you're keying on word now.$wordLength[$length]++becomes$wordLength{$length}++.