Skip to content

Instantly share code, notes, and snippets.

@ttakezawa
Created May 21, 2011 10:38
Show Gist options
  • Save ttakezawa/984425 to your computer and use it in GitHub Desktop.
Save ttakezawa/984425 to your computer and use it in GitHub Desktop.
tree(1) like command
#!/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