2015-09-07 70 views
1

我想知道是否有找到存在於具有特殊類型的文件夾中的文件數量。例如,我有一個帶有* .txt,* .doc和html擴展名的30個文件的文件夾。我想知道這個目錄中的say html文件的數量。計算perl中特殊類型的目錄中的文件數

更新:這裏是我作爲一個數字os文件在目錄中。但我不知道如何使用​​3210。當然,而不是getcwd可以給出另一個參數。

use Cwd; 
my $dir = getcwd; 
my $count = 0; 
opendir (DIR, $dir) or die $!; 
my @dir = readdir DIR; 
my @file_list; 

if (@file_list eq glob "*.pl"){ 
    print "$item\n"; 
    $count = $count + 1; 
} 

closedir DIR; 

$count = $count - 2; 
print "There are $count files in this directory."; 
+2

http://perldoc.perl.org/functions/glob.html –

+4

是的,有一種方法。 – melpomene

+2

顯示你的嘗試。 – Jens

回答

3

我發現瞭如何做到這一點不​​3210:

#!/usr/bin/perl 

use strict; 
use warnings; 
use Cwd; 

my $dir = getcwd; 
my $count = 0; 

opendir(my $dh, $dir) or die "$0: $dir: $!\n"; 
while (my $file = readdir($dh)) { 
    # We only want files 
    next unless (-f "$dir/$file"); 
    # Use a regular expression to find files ending in .txt 
    next unless ($file =~ m/\.html$/); 

    print "$file\n"; 
    $count = $count + 1; 
} 
closedir($dh); 
print "There are $count files in this directory."; 
exit 0; 

非常感謝您的意見!

+2

不錯,但我建議使用詞法變量而不是裸詞目錄句柄:'opendir(my $ dh,$ dir)或者死掉「$ 0:$ dir:$ !\ n「; ... readdir($ dh)' – melpomene

+1

如果您只想要當前目錄,則不需要'getcwd';你可以打開「'。'」。 – melpomene

+0

@melpomene非常感謝您的建議。我使用了第一個建議。好想法! – Royeh

2

你在問題中遇到的問題是glob有點神奇。你可以這樣做:

foreach my $file (glob ("*.txt")) { 
    print $file,"\n"; 
} 

while (my $file = glob ("*.txt")) { 
    print $file,"\n"; 
} 

無論你期待一個標量(單個值)返回水珠被檢測 - 在這種情況下,它可以作爲一個迭代器 - 或陣列(多標量) - 在這種情況下,它返回整個地段。

你可以把它做你想要的東西是這樣的:

my @stuff = glob ("*.txt"); 
print "There are: ", scalar @stuff," files matching the pattern\n"; 
print join ("\n", @stuff); 

注意readdir以同樣的方式 - 你可以發出聲音了一大堆列表中的情況下這樣做,或者在一次一行與標量上下文:

opendir (my $dirh, "some_directory"); 
my @stuff = readdir ($dirh); 

#etc. 

或者

opendir (my $dirh, ".") or die $!; 
while (my $dir_entry = readdir ($dirh)) { 
    #etc. 
} 

如果你想牛逼o不要READDIR和過濾器,你也可以做這樣的:

my @matches = grep { m/\.txt$/ } readdir ($dirh); 

例如(這不救你任何效率 - grep只是隱藏循環。這可能會使它更具可讀性 - 這是一個有趣的問題)。

相關問題