使用引用来遍历整个目录
#!/usr/bin/perl -w use strict; sub dir_walk { my ($top,$filefunc,$dirfunc) = @_; my $DIR; if (-d $top){ my $file; unless (opendir $DIR,$top){ warn "Coun't open the $top:$!;skipping.\n"; return; } my @results; while ( $file = readdir $DIR){ next if $file eq '.' || $file eq '..'; #递归统计文件的大小 push @results,dir_walk("$top/$file",$dirfunc); #print "$top/$file @results\n"; } #解dir_size引用 return $dirfunc->($top,@results); }else { #解file_size的引用 return $filefunc->($top); } } sub file_size { -s $_[0] }; sub dir_size { my $dir = shift; my $total = -s $dir; my $n; for $n (@_){$total += $n } #统计results的值和目录值 printf "%6d %s\n",$total,$dir; #打印每次循环的目录的大小和目录名 return $total; } my $total_size = dir_walk('/downloads/PHP/serv',\&file_size,\&dir_size); print "$total_size \n";