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


In reply to Re: Finding nested directories from a string list. by QM
in thread Finding nested directories from a string list. by superfrink

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.