in reply to How to map a directory tree to a perl hash tree

Here's another way. I handle the recursion myself, without File::Find. I used your example as a model.

Is this what you want or am I missing something?

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $dirth = &dirTreeHash(shift); sub dirTreeHash { my $dir = shift; return unless (defined $dir && -d $dir); $dir =~ s#\\#/#g; # Win32 :-( my $dirth = {}; opendir(DIR, $dir) || die "Unable to opendir $dir\n"; my @files = grep {!/^\.\.?$/} readdir(DIR); closedir(DIR); map {$dirth->{$_} = (-d "$dir/$_" ? &dirTreeHash("$dir/$_") : '')} @ +files; return $dirth; } $Data::Dumper::Indent = 1; print Dumper $dirth;

Replies are listed 'Best First'.
Re: Re: How to map a directory tree to a perl hash tree
by merlyn (Sage) on Mar 12, 2001 at 15:25 UTC

      Sorry Randal. How about if I change the line from

      map {$dirth->{$_} = (-d "$dir/$_" ? &dirTreeHash("$dir/$_") : '')} @fi +les;

      to

      map {$dirth->{$_} = (-d "$dir/$_" ? &dirTreeHash("$dir/$_") : '') unle +ss (-l "$dir/$_")} @files;
Re: Re: How to map a directory tree to a perl hash tree
by Rudif (Hermit) on Mar 12, 2001 at 01:44 UTC
    Is this what you want or am I missing something?
    Yes, it does exactly what I want.

    Now we have 3 solutions to compare:

    Yours is perhaps the most natural - a recursive solution for a recursive problem.
    japhy's solution neatly replaces recursion by iteration and enables the use of File::Find::find.
    Mine , deprecated because based on string eval, uses the information extracted with File::Find::find directly.

    All have similar complexity. Performance will probably be dominated by the disk access operations, not by the algorithm used.

    Rudif