我正在逐字读取文件(其中文件包含单词行)并将每个单词存储到哈希中。我想存储出现次数以及在哪一行找到单词(注意:我将根据单词本身对哈希进行排序,如代码所示)
我有(不工作)(假设单词数组正确存储了单词,没有特殊字符,并且是小写的):
my %wordlist;
my $line = 0;
foreach my $word (@words) {
$line++;
if (exists $wordlist{$word}) {
$wordlist{$word} += 1;
$wordlist{$line} = $wordlist{$line} . ", $line";
}
else {
$wordlist{$word} = 1;
$wordlist{$line} = "$line";
}
}
后来我尝试将 $wordlist{$line} 打印为字符串,在包含以下内容的循环内:
printf "%${length}s: %4d times, on lines %s\n", $key, $wordlist{$key}, $wordlist{$line};
运行时,我收到错误:
Use of uninitialized value in printf at ./wc.pl line 105, <FILE> line 20.
someWord: 2 time(s), line(s)
其中第 20 行是退出语句