http://www.chinaunix.net 作者:路小佳 本文介绍遍历文件夹方法:递归遍历。(遍历函数为lsr)
#!/usr/bin/perl -W # File: lsr.pl # License: GPL-2
use strict; use warnings;
sub lsr($) { sub lsr; my $cwd = shift;
local *DH; if (!opendir(DH, $cwd)) { warn "Cannot opendir $cwd: $! $^E"; return undef; } foreach (readdir(DH)) { if ($_ eq '.' || $_ eq '..') { next; } my $file = $cwd.'/'.$_; if (!-l $file && -d _) { $file .= '/'; lsr($file); } process($file, $cwd); } 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('.'); print "$filecnt files, $dircnt directory. $size bytes.\n"; 下面是对我的硬盘/dev/hda6的lsr测试结果:
26881 files, 1603 directory. 9052479946 bytes.
real 0m8.266s user 0m2.686s sys 0m5.405s |