M
Mathematisch
Hello,
Would someone please show how to create a tree data structure by using
an OS directory as input. So the nodes should be the names of the
directories and the leaves should represent each file. Each directory
should turn into a node and its files and sub directories will become
its children.
In this example, I have downloaded the Tree::Simple module from CPAN
and I know that Perl's File::Find module traverses a directory
recursively. I am stuck as I do not know how one can create a tree
object from the results of File::Find
Below is the code that I've tried on a directory with multiple sub
directories and files. It does not create the desired tree object:
#start of the failed code
use strict;
use warnings;
use File::Find;
use Tree::Simple;
use Data:umper;
my $tree = Tree::Simple->new("0", Tree::Simple->ROOT); #create the
root node
find(\&processCurrent, ('C:\PROJECTS\MyDir') ); #process all
directories and files
print Dumper $tree; #the desired tree is not created!
sub processCurrent {
if (-d) { #this is a directory
$tree = Tree::Simple->new($_, $tree); #create a new
subtree, take the last one as parent
}
elsif (-f) { #this is a file
$tree->addChild(Tree::Simple->new($_)); #add this file
to the current tree
}
}
#end of the failed code
Would someone please show how to create a tree data structure by using
an OS directory as input. So the nodes should be the names of the
directories and the leaves should represent each file. Each directory
should turn into a node and its files and sub directories will become
its children.
In this example, I have downloaded the Tree::Simple module from CPAN
and I know that Perl's File::Find module traverses a directory
recursively. I am stuck as I do not know how one can create a tree
object from the results of File::Find
Below is the code that I've tried on a directory with multiple sub
directories and files. It does not create the desired tree object:
#start of the failed code
use strict;
use warnings;
use File::Find;
use Tree::Simple;
use Data:umper;
my $tree = Tree::Simple->new("0", Tree::Simple->ROOT); #create the
root node
find(\&processCurrent, ('C:\PROJECTS\MyDir') ); #process all
directories and files
print Dumper $tree; #the desired tree is not created!
sub processCurrent {
if (-d) { #this is a directory
$tree = Tree::Simple->new($_, $tree); #create a new
subtree, take the last one as parent
}
elsif (-f) { #this is a file
$tree->addChild(Tree::Simple->new($_)); #add this file
to the current tree
}
}
#end of the failed code