#!/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 #### $nested{$path} = 1;