专注各种脚本编程
Baidu
加入收藏夹
本站内容有下面分类知识,欢迎您的到来^_^
shell相关:指令篇 基础篇 脚本欣赏 编程实例 shell问问 shell视频教程 技巧篇 水平测试 E文资料 vi编辑器 高级Bash脚本编程指南
其他:mysql perl c语言 oracle
当前位置:| 主页>perl>

perl遍历文件夹的方法-lsr递归遍历

百度收藏 QQ搜藏

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

上一篇:perl遍历文件夹的方法-使用File::Find 下一篇:perl遍历文件夹的方法-使用队列或栈遍历

power by soyo123 2007-2008