Perl实现遍历目录例子
环境为windos,需要注意的两点:
1、默认activePerl下的采用的编码是gbk,所以需要将字符串转为gbk才不会显示乱码
2、遍历文件目录时,需要排除特殊的目录.和..
完整的代码:
代码如下:
#!/usr/bin/perl use strict; use warnings; use Encode qw/from_to/; my $path = "e:/CSS Design"; my $filecount = 0; sub parse_env { my $path = $_[0]; #或者使用 my($path) = @_; @_类似javascript中的arguments my $subpath; my $handle; if (-d $path) {#当前路径是否为一个目录 if (opendir($handle, $path)) { while ($subpath = readdir($handle)) { if (!($subpath =~ m/^\.$/) and !($subpath =~ m/^(\.\.)$/)) { my $p = $path."/$subpath"; if (-d $p) { parse_env($p); } else { ++$filecount; print $p."\n"; } } } closedir($handle); } } return $filecount; } my $count = parse_env $path; my $str = "文件总数:".$count; from_to($str, "utf8", "gbk"); print $str;
运行效果图:
相关推荐
边城客栈学无止境 2020-07-05
Walter的学习笔记 2020-07-04
A宇 2020-06-14
边城客栈学无止境 2020-06-10
邓博学习笔记 2020-06-03
davidliu00 2020-05-26
ShiShuo 2020-05-16
Aggressivesnail 2020-05-10
ShiShuo 2020-04-26
hanxingwang00 2020-04-22
davidliu00 2020-03-06
ShiShuo 2020-03-06
ShiShuo 2020-03-05
Aggressivesnail 2020-02-28
aaLiweipeng 2020-02-01
amberom 2020-01-16
Walter的学习笔记 2020-01-06