in reply to Finding nested directories from a string list.

Something like this?
#!/your/perl/here use strict; use warnings; my @paths = ( 'C:\\foo\\bar\\baz', 'C:\\foo\\bar', 'C:\\car', 'C:\\c' ); # remove duplicates my %paths; @paths{@paths} = (1) x @paths; # create the tree of paths seen my $tree = {}; foreach my $path ( keys %paths ) { my @dirs = split /\\+/, $path; # insert in hash my $node = $tree; foreach my $dir ( @dirs ) { if ( exists( $node->{LEAF} ) ) { print "$path\n"; } # create the next nested hash if needed $node->{$dir} = {} unless exists $node->{$dir}; # move pointer down a level $node = $node->{$dir}; } # if there are keys at this level (other than LEAF) my $keys = keys %{$node}; if ( ( $keys > 1 ) or ( ( $keys == 1 ) and ( exists $node->{LEAF} ) ) ) { print "$path\n"; } # mark this as a leaf $node->{LEAF}=1; } __OUTPUT__ C:\foo\bar\baz
Instead of printing those out, you could just as easily add them to a hash for further processing:
$nested{$path} = 1;

Update: Fixed typo in exists that the compiler didn't catch (??).

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^2: Finding nested directories from a string list.
by superfrink (Curate) on Feb 27, 2006 at 16:24 UTC
    This is great QM ! I had to make one change due to the order that keys are pulled out of a hash. I changed the code from:
    foreach my $path ( keys %paths ) {
    to:
    # : N.B. We explicitly iterate over the paths in order of the # number of directory components. This is so we don't create # directories for a child path before creating directories for a # parent path. # : sort the keys to %path by the number of directory components and # then by a string compare. (both comparisons are ascending.) my @sorted_paths = sort { $a =~ tr/\\// <=> $b =~ tr/\\// || $a cmp $b } keys %paths; # : foreach $path in the @sorted_paths array foreach my $path (@sorted_paths) {
      As was stated elsewhere in this thread, you can sort on length instead. The parent will always sort before the child:
      my @sorted_paths = sort { length($a) <=> length($b) } keys %paths;

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of