Greg W
Greg W

Reputation: 13

Perl: Using hash instead of array

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
}

Upvotes: 0

Views: 44

Answers (1)

ikegami
ikegami

Reputation: 385506

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;
}

Upvotes: 1

Related Questions