Perl:使用哈希而不是数组

时间:2017-06-02 00:28:30

标签: arrays perl hash

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

这可以很好地读取txt文件并输出如下:

Word Length  Occurrence
1            27 
2            104 
3            1039 
4            3505 
5            7181 
6            11765 
7            15898 

我试图使用哈希而不是数组来使用它,但它似乎不起作用。这是我的尝试:

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
}

1 个答案:

答案 0 :(得分:1)

为什么呢?任何阵列在这里都很有效。

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

哈希虽然效率较低,但可以轻松使用,无需更改。

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