【发布时间】:2010-02-11 08:33:35
【问题描述】:
下面的两个例子都可以,还是第二个例子不好?
案例1:留在顶层目录,使用catdir访问子目录
#!/usr/bin/env perl
use warnings; use strict;
my $dir = 'my_dir_with_subdir';
my ( $count, $dh );
use File::Spec::Functions;
$count = 0;
opendir $dh, $dir or die $!;
while ( defined( my $file = readdir $dh ) ) {
next if $file =~ /^\.{1,2}$/;
my $sub_dir = catdir $dir, $file;
if ( -d $sub_dir ) {
opendir my $dh, $sub_dir or die $!;
while ( defined( my $file = readdir $dh ) ) {
next if $file =~ /^\.{1,2}$/;
$count++;
}
closedir $dh or die $!;
}
else {
$count++;
}
}
closedir $dh or die $!;
print "$count\n";
案例2:切换到子目录,退出前恢复顶层目录
use Cwd;
my $old = cwd;
$count = 0;
opendir $dh, $dir or die $!;
chdir $dir or die $!;
while ( defined( my $file = readdir $dh ) ) {
next if $file =~ /^\.{1,2}$/;
if ( -d $file ) {
opendir my $dh, $file or die $!;
chdir $file or die $!;
while ( defined( my $file = readdir $dh ) ) {
next if $file =~ /^\.{1,2}$/;
$count++;
}
closedir $dh or die $!;
chdir $dir;
}
else {
$count++;
}
}
closedir $dh or die $!;
chdir $old or die $!;
print "$count\n";
【问题讨论】:
-
不要隐藏你的主要问题!你的读者不应该在混合在一起的两段代码之间做
diff。 -
它并没有直接解决你的问题,但是 Higher Order Perl 是一本很棒的书 (hop.perl.plover.com)。第一章使用目录遍历作为递归和回调的有用案例研究。
-
这一章我会看的,不过如果我没记错的话,这本书的水平对我来说太高了。