2009-10-02 97 views
9

我正在使用此代碼來獲取所有文件的特定目錄的列表:如何從特定目錄中獲取具有特定擴展名的所有文件的列表?

opendir DIR, $dir or die "cannot open dir $dir: $!"; 
my @files= readdir DIR; 
closedir DIR; 

我怎麼能修改此代碼或追加的東西,以便它僅查找文本文件,只加載具有文件名前綴的數組?

實例目錄內容:

. 
.. 
923847.txt 
98398523.txt 
198.txt 
deisi.jpg 
oisoifs.gif 
lksdjl.exe 

實例數組內容:

files[0]=923847 
files[1]=98398523 
files[2]=198 
+0

另外考慮爲你的目錄句柄使用一個詞法變量:'opendir my $ dirh,$ dir_path or die「無法打開dir $ dir:$!」;' – 2009-10-02 16:30:37

回答

10
my @files = glob "$dir/*.txt"; 
for (0..$#files){ 
    $files[$_] =~ s/\.txt$//; 
} 
+0

任何想法如何將該目錄重新排列呢?我的輸出是/ dir/dir/dir/923847 ...我怎麼才能得到923847? – CheeseConQueso 2009-10-02 15:50:37

+0

glob在這裏添加額外的工作。請參閱http://stackoverflow.com/questions/1506801/what-reasons-are-there-to-prefer-glob-over-readdir-or-vice-versa-in-perl – 2009-10-02 16:09:59

5

它是足以改變一個行:

my @files= map{s/\.[^.]+$//;$_}grep {/\.txt$/} readdir DIR; 
2

得到公正的」。 txt「文件,您可以使用文件測試操作ator(-f:常規文件)和一個正則表達式。

my @files = grep { -f && /\.txt$/ } readdir $dir; 

否則,你可以看看只是文本文件,使用Perl的-T(ASCII文本文件測試操作)

my @files = grep { -T } readdir $dir; 
+0

-T用於測試您是否擁有「textfile」 – reinierpost 2009-10-02 16:38:43

+0

好點;從運營商的perldoc頁面(http://perldoc.perl.org/5.8.8/perlfunc.html),「-T \t文件是ASCII文本文件(啓發式猜測)。」如果他正在尋找「.txt」文件,這將完全按照他未經猜測的方式進行。 – 2009-10-02 16:44:26

3

如果你可以使用Perl 5.10的新功能,這是怎麼了我會寫它。

use strict; 
use warnings; 
use 5.10.1; 
use autodie; # don't need to check the output of opendir now 

my $dir = "."; 

{ 
    opendir my($dirhandle), $dir; 
    for(readdir $dirhandle){ # sets $_ 
    when(-d $_){ next } # skip directories 
    when(/^[.]/){ next } # skip dot-files 

    when(/(.+)[.]txt$/){ say "text file: ", $1 } 
    default{ 
     say "other file: ", $_; 
    } 
    } 
    # $dirhandle is automatically closed here 
} 

或者,如果你有非常大的目錄,你可以使用一個while循環。

{ 
    opendir my($dirhandle), $dir; 
    while(my $elem = readdir $dirhandle){ 
    given($elem){ # sets $_ 
     when(-d $_){ next } # skip directories 
     when(/^[.]/){ next } # skip dot-files 

     when(/(.+)[.]txt$/){ say "text file: ", $1 } 
     default{ 
     say "other file: ", $_; 
     } 
    } 
    } 
} 
1

只要使用此:

my @files = map {-f && s{\.txt\z}{} ? $_ :()} readdir DIR; 
1

這是我發現的最簡單的方法(如人類可讀)使用的glob功能:

# Store only TXT-files in the @files array using glob 
my @files = grep (-f ,<*.txt>); 
# Write them out 
foreach $file (@files) { 
    print "$file\n"; 
} 

此外,該「-f 「確保只有實際文件(而不是目錄)存儲在數組中。

+0

爲什麼回滾編輯? 'foreach $ file'並不嚴格安全。如果你喜歡'foreach'來'for',爲什麼不'foreach我的$ file'? – 2015-07-27 14:22:50

+0

爲什麼編輯某人刪除舊的東西,當你不知道爲什麼它張貼在第一個地方的原因?地獄我甚至不知道爲什麼我在三年前編寫這段代碼的原因,但由於我有一個測試事情的習慣,它可能工作得很好,並且可能有一個原因,我沒有在嚴格聲明。但是,這是否意味着我應該接受一個隨機編輯,我是否還想花時間測試它?一定不行!這就是爲什麼我發現將它回滾更安全的原因。 – Kebman 2015-07-28 09:59:39

+0

要說清楚,我不是編輯它,我只是看到了編輯,並認爲它改進了答案。您使用詞法'@ files'然後是全局'$ file'就很奇怪。 – 2015-07-28 16:00:33

相關問題