August 28, 2008

I needed to print out an ASCII representation of a directory structure.

I'm sure there is probably some simple built in unix command line tool that does this automatically, but what fun would that be?

Here is the result:

use warnings;
use strict;
use Tree::Simple;
use Tree::Simple::Visitor::LoadDirectoryTree;
use Tree::Simple::View::ASCII;
use Cwd;

my $dir = shift(@ARGV) || cwd();
if (!-d $dir) {
die "$dir is not a directory, smart ass.";

# create a Tree::Simple object whose
# node is path to a directory
my $tree = Tree::Simple->new($dir);
my $visitor = Tree::Simple::Visitor::LoadDirectoryTree->new();

# set the directory sorting style
$visitor->setSortStyle( $visitor->SORT_FILES_FIRST );

# create node filter to filter
# out certain files and directories
sub {
my ($item) = @_;
return 0 if ($item =~ /CVS|svn/ || ($item =~ /^.*/ && -f $item));
return 1;

# pass the visitor to a Tree::Simple object

my $tree_view = Tree::Simple::View::ASCII->new($tree);
print $tree_view->expandAll();


Posted by ed at 11:51 AM