0
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
}
4
  • 1
    Why not $wordLength{$length}? It's super odd you're keying on word now. Commented Jun 2, 2017 at 0:34
  • 1
    If you still want counts of each length, then you only need to change the brackets from your original code: $wordLength[$length]++ becomes $wordLength{$length}++. Commented Jun 2, 2017 at 1:22
  • 1
    Also, "it doesn't seem to work" is not a valid problem description. What is your code actually doing? How is that different from what you expect? Commented Jun 2, 2017 at 1:24
  • 1
    Can you please clearly state what you need? If it is the output shown under "This works great reading" then your hash attempt clearly has nothing to do with that. You are storing words as keys (not lengths) and you aren't counting. (Is this a homework by any chance?) Commented Jun 2, 2017 at 3:36

1 Answer 1

1

Why? Any array works great here.

my @occurrences_by_length;
while (my $word = <>) {
   chomp($word);
   my $length = length($word);
   ++$occurrences_by_length[$length];
}

print "Length  Occurrences\n";
for my $length (1..$#occurrences_by_length) {
   my $occurrences = $occurrences_by_length[$length]
      or next;

   printf "%6d  %11d\n", $length, $occurrences;
}

A hash, while less efficient, could easily be used with next to no changes.

my %occurrences_by_length;
while (my $word = <>) {
   chomp($word);
   my $length = length($word);
   ++$occurrences_by_length{$length};
}

print "Length  Occurrences\n";
for my $length (sort { $a <=> $b } keys(%occurrences_by_length)) {
   my $occurrences = $occurrences_by_length{$length};
   printf "%6d  %11d\n", $length, $occurrences;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.