isync has asked for the wisdom of the Perl Monks concerning the following question:

I use File::Find to traverse a directory in order to build a nested data structure from the found items which I'd like to feed to a Wx TreeCtrl.

Problem is, I seem to be too tired to get the right algorithm to construct nested stuff. I know I need a recursive call of some sort, but today all I could come up with was good enough for a somehow sorted data structure as result.

Anyone out there who can quickly copy and past some code for me from a previous project as this surely was solved a million times before?
sub Load { my $dir = shift; find(\&wanted, $dir); for(keys %tree){ my $name = $_; $name =~ s/^$dir//; push( @{ $tree }, { name => $name, value=> 1, # $tree{ $_ } } ); } print Dumper($tree); return $tree; } sub wanted { my $self = shift; push( @{ $tree{ $File::Find::dir } }, $_ ); }

Replies are listed 'Best First'.
Re: Building a nested data structure from File::Find
by onelesd (Pilgrim) on Jun 09, 2011 at 22:02 UTC
      I didn't come across this one when I had a look around cpan. Thanks for the hint! I'll have a look.
Re: Building a nested data structure from File::Find
by wind (Priest) on Jun 09, 2011 at 23:27 UTC
    Use an embedded sub in situations like this. Will make it easier read your code and to build your local data structure.
    sub Load { my $dir = shift; my %tree; find(sub { push @{$tree{ $File::Find::dir }}, $_; }, $dir); ... }
Re: Building a nested data structure from File::Find
by Anonymous Monk on Jun 10, 2011 at 00:29 UTC
Re: Building a nested data structure from File::Find
by isync (Hermit) on Jun 10, 2011 at 15:54 UTC
    Thanks for the hints!

    If anyone is interested, my result:
    my $tb = Tree::Builder->new(); find(sub { my $name = $File::Find::name; $name =~ s/^$dir//; $tb->add($name); }, $dir); my $tree = { $tb->getTree }; _transformTree( $tree ); ... sub _transformTree { my $ref = shift; ## I need sort of meta-data-enabled tree: foreach my $item (keys %$ref){ if( keys %{ $ref->{ $item } } ){ my $clone = $ref->{ $item }; $ref->{ $item } = {}; $ref->{ $item }->{name} = $item; $ref->{ $item }->{value} = $clone; # $clone = undef; # should I uncomment this? or does perl +take care of it? _transformTree( $ref->{ $item }->{value} ); }else{ $ref->{ $item }->{name} = $item; $ref->{ $item }->{value} = undef; } } }