Perl遍历目录

环境为windos,需要注意的两点:

1、默认activePerl下的采用的编码是gbk,所以需要将字符串转为gbk才不会显示乱码

2、遍历文件目录时,需要排除特殊的目录.和..

完整的代码:

 

   1: #!/usr/bin/perl
   2: use strict;
   3: use warnings;
   4: use Encode qw/from_to/; 
   5:  
   6: my $path = "e:/CSS Design";
   7: my $filecount = 0; 
   8:  
   9: sub parse_env {    
  10:     my $path = $_[0]; #或者使用 my($path) = @_; @_类似javascript中的arguments
  11:     my $subpath;
  12:     my $handle; 
  13:  
  14:     if (-d $path) {#当前路径是否为一个目录
  15:         if (opendir($handle, $path)) {
  16:             while ($subpath = readdir($handle)) {
  17:                 if (!($subpath =~ m/^\.$/) and !($subpath =~ m/^(\.\.)$/)) {
  18:                     my $p = $path."/$subpath"; 
  19:  
  20:                     if (-d $p) {
  21:                         parse_env($p);
  22:                     } else {
  23:                         ++$filecount;
  24:                         print $p."\n";
  25:                     }
  26:                 }                
  27:             }
  28:             closedir($handle);            
  29:         }
  30:     } 
  31:  
  32:     return $filecount;
  33: } 
  34:  
  35: my $count = parse_env $path;
  36: my $str = "文件总数:".$count;
  37: from_to($str, "utf8", "gbk"); 
  38:  
  39: print $str; 

 

 

运行效果图:

 

image

posted @ 2011-01-12 00:19 meteoric_cry 阅读(...) 评论(...) 编辑 收藏