我正在尝试使用来自目录中所有文本文件的单词来填充数组的散列。单词用作键,文件名用作与键相关联的标量值。在Perl中填充和搜索数组的散列?
我正在使用数组的散列,因为一个单词可能很容易在另一个文本文件中重复。我想填写散列表;那么我想通过关键词搜索来确定哪些文件包含一些给定的关键字。
我的代码的摘录:
# Search term(s).
my @search_terms = ("random", "searches");
opendir(DIR, $directory) or die $!;
@files = grep(/\.txt$/, readdir(DIR)) or die("you idiot");
# Create a hash table to store the words as keys and the file name.
my %hash;
# Go through the files, grab the words, and create hash table.
foreach my $file(@files) {
open(FILE,"<$file") or die $!;
while(<FILE>){
chomp;
my @words = split(' ');
# Store the key, value pairs for each file.
# Key is the word.
# Value is the file name.
foreach my $word(@words) {
push @{$hash{$word}}, $file;
}
}
close(FILE);
}
# Go through each search term.
foreach my $match(@search_terms) {
# If a key exists in the hash table, then we have a matched result.
if($hash{$match}) {
# Print the file name (scalar value for word key).
print "$hash{$match} matched.";
print "\n";
}
}
看来,也许我没有正确填写我的哈希(或者我只是不知道如何打印数组的哈希值)。另外,我的匹配对于文件不正确。任何帮助,我做错了什么将不胜感激!谢谢!