我正在嘗試使用來自目錄中所有文本文件的單詞來填充數組的散列。單詞用作鍵,文件名用作與鍵相關聯的標量值。在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";
}
}
看來,也許我沒有正確填寫我的哈希(或者我只是不知道如何打印數組的哈希值)。另外,我的匹配對於文件不正確。任何幫助,我做錯了什麼將不勝感激!謝謝!