今天在学习perl的递归方式时,编写了一段代码,用来递归遍历指定目录下的所有子目录以及文件,具体代码如下:
#################################################################################
#功能:此程序用于搜索指定目录下的所有文件以及该目录下包括子目录在内的所有文件 #
#日期:2011-01-17 #
#编写:Edwin Zhou #
#################################################################################
#!/usr/bin/perl
use strict;
#use Data::Dumper;
my $search_folder = '/home/zhoucg/convertlog_tmp';
sub data_for_path {
my $path = shift;
if (-f $path or -l $path) {
return undef;
}
if (-d $path) {
my %directory;
opendir PATH, $path or die "Cannot opendir $path: $!\n";
my @names = readdir PATH;
closedir PATH;
for my $name (@names) {
next if $name eq '.' or $name eq '..';
$directory{$name} = data_for_path("$path/$name");
}
return \%directory;
}
warn "$path is neither a file nor a directory\n";
return undef;
}
#print Dumper(data_for_path('.'));
sub dump_data_for_path {
my $path = shift;
my $data = shift;
if (not defined $data) {
print "$path\n";
return;
}
my %directory = %$data;
for (sort keys %directory) {
dump_data_for_path("$path/$_",$directory{$_});
}
}
dump_data_for_path("$search_folder", data_for_path("$search_folder"));
阅读(3341) | 评论(2) | 转发(0) |