Created
May 21, 2011 10:38
-
-
Save ttakezawa/984425 to your computer and use it in GitHub Desktop.
tree(1) like command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
my $dir_cnt = -1; | |
my $file_cnt = 0; | |
sub visit { | |
my ($dirname, $line_prefix) = @_; | |
$dir_cnt++; | |
opendir(my $dh, $dirname) || die "can't opendir $dirname: $!"; | |
my @paths = sort(grep { /^[^\\.]/ } readdir $dh); | |
closedir $dh; | |
my $loop_cnt = 0; | |
for my $path (@paths) { | |
$loop_cnt++; | |
my $is_last = $loop_cnt == scalar(@paths); | |
my $fullpath = "$dirname/$path"; | |
my $entry = ($is_last ? "`-- " : "|-- ") . $path; | |
if (-l $fullpath) { | |
my $link_path = readlink($fullpath); | |
print "$line_prefix$entry -> $link_path\n"; | |
# If this is a symlink to a normal file, increment file count. | |
-f $link_path ? $file_cnt++ : $dir_cnt++; | |
next; | |
} | |
print "$line_prefix$entry\n"; | |
if (-d _) { | |
visit($fullpath, $line_prefix . ($is_last ? " " : "|") . " "); | |
} else { | |
$file_cnt++; | |
} | |
} | |
} | |
my $dir = shift @ARGV || "."; | |
print $dir, "\n"; | |
visit($dir, ""); | |
print "\n"; | |
print "$dir_cnt directories, $file_cnt files\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment