Perl Scripts / 脚本

  • 树状递归列出目录下面子目录和文件
#!/usr/bin/perl
#List all files and sub-directories as tree
#Under current directory, or directory specified in command line

use strict;
use warnings;
use File::Spec::Functions qw(catdir splitdir);

my $curdir = @ARGV ? $ARGV[0] : '.';
unless (-d $curdir) { die "$curdir is not directory." }

tree($curdir, 0);
exit 0;

sub tree {
    my ($dir, $depth)=@_;
    my @directories = grep{$_} splitdir($dir);
    my $short_name = $directories[-1];
    my $prefix = '|  ' x $depth;
    print "$prefix$short_name/\n";
    opendir (my $dh, $dir);
    my @entries = grep{ !/^\./ } readdir($dh);
    foreach my $entry (@entries){
        #my $path = catdir($dir, $entry);   #List full path of file
        my $path=$entry;                          #List files
        if (-f $path ){ print "$prefix|--$path\n";}
        elsif (-d _) {tree ($path, $depth+1);}
        else { }
    }
}

 

posted @ 2017-03-04 22:03  tang88seng  阅读(579)  评论(0编辑  收藏  举报