Perl获取目录下文件或者包含子目录下文件

 1 my $dir = "D:\\My_Work\\Temp";
 2 my @files = ();
 3 
 4 #获取给定目录下文件
 5 @files = get_dir_files($dir);    
 6 
 7 #获取给定目录以及子目录下文件
 8 @files = get_dir_files_x($dir);
 9 
10 #获取目录下以及子目录下文件,返回的结果中包含路径
11 sub get_dir_files_x{
12     my ($dir_p) = @_;
13     my @files = ();
14     my @dirs = ($dir_p);
15     die "error $basedir: $!" unless(-d $dir_p);
16     while(@dirs){
17         $dir = $dirs[0];
18         opendir folder, $dir || die "Can not open this directory";
19         my @filelist = readdir folder; 
20         closedir folder;
21         foreach  (@filelist) {
22             next if ($_ eq "." or $_ eq "..");
23             my $f = path_join($dir,$_);
24             push(@dirs,$f) if (-d $f);
25             push(@files,$f) if (-f $f);
26         }
27         shift(@dirs);
28     }
29     return @files;
30 }
31 
32 #获取目录下文件
33 sub get_dir_files{
34     my ($dir) = @_;
35     my @files = ();
36     opendir DIR,$dir or die "Can not open this dir";
37     my @file_list = readdir DIR;
38     closedir DIR;
39     foreach(@file_list) {
40         push(@files,$_) if(-f path_join($dir,$_));
41     }
42     return @files;
43 }
44 
45 #获取路径合并操作,自动加上斜杠,有斜杠与没斜杠都可以合并
46 sub path_join{
47     my ($path1,$path2) = @_;
48     my $path = $path1."\\".$path2;
49     $path=~s/[\\|\/]+/\\/g;
50     return $path;
51 }

 

posted @ 2015-08-13 00:44  CodeTracker  阅读(2489)  评论(0编辑  收藏  举报