標籤:
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 }
Perl擷取目錄下檔案或者包含子目錄下檔案