这是小骆驼书第六章的第二道练习题,觉得非常经典,故记录于此:
问题:有一列单词,每行仅一个词,这些词中有一些是重复出现的,写一个程序统计每个单词出现的次数。
#!/usr/bin/perl use strict; use warnings; open INPUT,"<","input.txt"; open OUTPUT,"<","out.txt"; my (%count,$word); while(<INPUT>){ chomp; $count{$_}++; } foreach $word(keys %count){ print OUTPUT "$word was seen $count{$word} times.\n"; } close INPUT; close OUTPUT;
要点:在第一个foreach循环里,每次出现的单词都会让$count{$_}的值加1,假设第一个单词是fred,则$count{“fred”}的值就会加1。因为第一次用到$count{“fred”},它的值是undef。不过,由于我们将它当成数字来用,所以perl会自动把undef转换成0。相加的总和为1,所以会将1存回$count{“fred”}。
尊重他人劳动成果,转载请注明出处:Bluesky's blog » perl应用-哈希(hash)计数