2014-01-27 124 views
2

我有一個文本文件,其中包含一個單獨的助記符(1000+)列表和一個目錄,其中也包含頁面文件。我想看看給定的助記符有多少頁。下面如何檢查一個文件是否在一個目錄

是到目前爲止我的代碼..

use strict; 
use warnings; 
use File::Find(); 

my $mnemonics = "path\\path\\mnemonics.txt"; 
my $pages = "path\\path\\pages\\"; 

open (INPUT_FILE, $names) or die "Cannot open file $mnemonics\n"; 
my @mnemonic_list = <INPUT_FILE>; 
close (INPUT_FILE); 

opendir (DH, $pages); 
my @pages_dir = readdir DH; 

foreach my $mnemonic (@mnemonic_list) { 
    foreach my $page (@pages_dir) { 
     if (-e $mnemonic) { 
      print "$mnemonic is in the following page: $page"; 
     } else { 
      print "File does not exist \n"; 
     } 
    } 
} 

基本上,在那裏我知道一個名字在頁面存在,它沒有顯示我正確的輸出。當我知道它時,我收到很多「文件不存在」。

此外,而不是(-e)我試着使用:

if ($name =~ $page) 

,但這並沒有工作,要麼..

請幫幫忙!

+0

什麼助記符做項目的樣子? – ooga

+0

他們只是單詞,輸入新行。大約1000字+ –

+0

你想查看文件內部還是文件名? – ooga

回答

1

假設你要搜索的一個目錄充滿文本文件和打印包含從mnemonics.txt的單詞文件的名稱,試試這個:

use strict; use warnings; 

my $mnemonics = "path/mnemonics.txt"; 
my $pages = "path/pages/"; 

open (INPUT_FILE, $mnemonics) or die "Cannot open file $mnemonics\n"; 
chomp(my @mnemonic_list = <INPUT_FILE>); 
close (INPUT_FILE); 

local($/, *FILE);   # set "slurp" mode 
for my $filename (<$pages*>) { 
    next if -d "$filename"; # ignore subdirectories 
    open FILE, "$filename"; 
    binmode(FILE); 
    $filename =~ s/.+\///; # remove path from filename for output 
    my $contents = <FILE>; # "slurp" file contents 
    for my $mnemonic (@mnemonic_list) { 
    if ($contents =~ /$mnemonic/i) { 
     print "'$mnemonic' found in file $filename\n"; 
    } 
    } 
    close FILE; 
} 
+0

頁面目錄中沒有文本文件 –

+0

真棒這工作得很好!除了一件事......如果有多個頁面出現,該怎麼辦?它只輸出助記符所在的第一頁... –

+0

沒問題,實際上它只讀取總共1頁。永遠。 –

相關問題