perl-查询某目录及其子目录下的某类匹配文件

1、使用find

use strict;

use File::Find;

my @path = 'e:/xampp';

push (@path,'e:/xampp');

push (@path,'d:/eclipse-reporting-galileo-SR2-win32');

sub wanted {

if ( -f $File::Find::name ) {

if ( $File::Find::name =~ /\.xml$/ ) {

print "$File::Find::name\n";

}

}

}

find( \&wanted, @path );

2、自己写代码

#取出某个目录含子目录的特定文件

#程序:刘兴

#时间:2010.3.19

#blog:http://deepfuture.iteye.com

#QQ:782322192

use 5.010;

use warnings;

use strict;

my $dirs='D:\Boa Constructor';# 初始路径

my $lsfile;

my @filedir;

my %filediryj;#已经访问过的目录 ,目录名=>文件数目

my $flcount;

my $ppfile;#文件匹配符 以正则方式表达的

$ppfile='\.py$'; #文件匹配符 以正则方式表达的 ,这里是*.py

unshift (@filedir,$dirs);

$|=1;

my $filedir;

while ($filedir=shift(@filedir)){

opendir DH,$filedir or die "不能打开$filedir"; #打开目录

say "=======================================";

next if exists $filediryj{$filedir};#如果目录已经访问过了就不再访问

$flcount=0;

foreach $lsfile(readdir DH){#读取目录

next if $lsfile=~m/^\./;

$lsfile="$filedir\\$lsfile";

if ( -d $lsfile){

unshift (@filedir,$lsfile);

}

elsif ($lsfile=~m/$ppfile/i) {

$flcount++;

say $lsfile;#匹配到的文件名

}

}

close DH;

$filediryj{$filedir}=$flcount;#目录下共有多少个文件,使用哈希

say "目录$filedir下共$flcount个匹配文件";

}

say "=======================================";

say "查询结果统计";

#访问哈希列表

$flcount=0;

my $key;

my $value;

while (($key,$value)=each %filediryj){

say "$key目录文件数目:$value";

$flcount+=$value;

}

say "共有$flcount个文件匹配";

转自:

http://deepfuture.iteye.com/blog/619998