2009-11-05 149 views
1

我正在努力使用目錄樹來檢查多個目錄中是否存在文件。我使用Perl,而且我只能使用File::Find,因爲我無法爲此安裝任何其他模塊。在perl中檢查給定目錄格式的文件是否存在

這裏的文件系統我要穿越的佈局:

 
Cars/Honda/Civic/Setup/config.txt 
Cars/Honda/Pathfinder/Setup/config.txt 
Cars/Toyota/Corolla/Setup/config.txt 
Cars/Toyota/Avalon/Setup/ 

注意最後Setup文件夾缺少config.txt文件。

編輯:另外,在每個Setup文件夾中還有許多其他文件以及Setup文件夾和Setup文件夾。實際上沒有任何單個文件需要進行搜索才能進入Setup文件夾本身。

所以你可以看到文件路徑保持不變,除了make和model文件夾。我想查找所有安裝文件夾,然後檢查該文件夾中是否有config.txt文件。

起初我用下面的代碼與File::Find

my $dir = '/test/Cars/'; 
find(\&find_config, $dir); 

sub find_config { 
    # find all Setup folders from the given top level dir 
    if ($File::Find::dir =~ m/Setup/) { 
     # create the file path of config.txt whether it exists or not, well check in the next line 
     $config_filepath = $File::Find::dir . "/config.txt"; 
     # check existence of file; further processing 
     ... 
    } 
} 

可以很明顯的看到在試圖使用$File::Find::dir =~ m/Setup/,因爲它會返回一個命中的設置文件夾中的每一個文件的缺陷。有沒有辦法使用-d或某種目錄檢查而不是文件檢查? config.txt並不總是在文件夾中(如果它不存在,我需要創建它),所以我不能使用return unless ($_ =~ m/config\.txt/)之類的東西,因爲我不知道它是否存在。

我試圖找到一種方法來使用像return unless (<is a directory> and <the directory has a regex match of m/Setup/>)

也許File::Find不是這樣的東西的正確方法,但我一直在尋找一段時間沒有任何良好的線索與目錄名稱,而不是文件名稱的工作。

+1

爲什麼你不能安裝任何其他模塊? – Ether 2009-11-05 17:23:57

+0

由於批准它們在生產機器上使用的漫長過程,我對使用任何其他模塊猶豫不決。 – seano 2009-11-05 18:01:04

回答

0

我試圖找到一種方法來使用像return unless (<is a directory> and <the directory has a regex match of m/Setup/>)

use File::Spec::Functions qw(catfile); 

my $dir = '/test/Cars/'; 

find(\&find_config, $dir); 

sub find_config { 
    return unless $_ eq 'Setup' and -d $File::Find::name; 
    my $config_filepath = catfile $File::Find::name => 'config.txt'; 
    # check for existence etc 

} 
+0

非常感謝。他讓我走上了正確的道路,你幾乎完全放棄了這一切。 – seano 2009-11-05 17:42:18

4

File :: Find也查找目錄名稱。你想檢查什麼時候$_ eq 'Setup'(注意:eq,不是你的正則表達式,它也會匹配XXXSetupXXX),然後查看目錄中是否有config.txt文件(-f "$File::Find::name/config.txt")。如果您想避免抱怨名爲Setup的文件,請檢查找到的「Setup」是否爲-d的目錄。

+0

@brian d foy:謝謝 – ysth 2009-11-06 04:33:44

相關問題