perl 实现du目录的脚本

前端之家收集整理的这篇文章主要介绍了perl 实现du目录的脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用引用来遍历整个目录

#!/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";

猜你在找的Perl相关文章