perl 遍历文件夹
由于程序需要遍历文件夹,上baidu找资料。找到
http://hi.baidu.com/%E7%BE%BD%E6%AE%87%E4%BB%81/blog/item/9e1be5f5bb194223bd310945.html
lsr_s栈遍历
#!/usr/bin/perl -W # # File: lsr_s.pl # Author: 路小佳 # License: GPL-2 use strict; use warnings; sub lsr_s($) { my $cwd = shift; my @dirs = ($cwd.'/'); my ($dir, $file); while ($dir = pop(@dirs)) { local *DH; if (!opendir(DH, $dir)) { warn "Cannot opendir $dir: $! $^E"; next; } foreach (readdir(DH)) { if ($_ eq '.' || $_ eq '..') { next; } $file = $dir.$_; if (!-l $file && -d _) { $file .= '/'; push(@dirs, $file); } process($file, $dir); } closedir(DH); } } my ($size, $dircnt, $filecnt) = (0, 0, 0); sub process($$) { my $file = shift; print $file, "\n"; if (substr($file, length($file)-1, 1) eq '/') { $dircnt++; } else { $filecnt++; $size += -s $file; } } lsr_s('.'); print "$filecnt files, $dircnt directory. $size bytes.\n"; |
相关文章
原创文章如转载,请注明:转载自 记录我的网赚生活 [ http://www.yed.info/ ]
本文链接地址:http://www.yed.info/archives/42.html
后来在 http://bbs3.chinaunix.net/viewthread.php?tid=907555 发现了原始出处
——————————
(-d $file && !-l $file)
类似这样的操作,第2个$file可以用_替换吧?表示重用前一个文件句柄.
——————————
比如像(!-l $file && -d _)这种, 刚才测试有了了1%~5%的提升
——————————
Perl best practice里有讲这些的
——————————
自己会的perl还是太少了,怪不得写的程序性能没那么好呢,还得好好学习