use strict; use warnings; use Algorithm::Loops qw( NestedLoops ); my $tree = { A => '', B => 'A', C => 'A', D => 'C', E => 'C', F => 'B', G => 'D', H => 'D', I => 'D', J => 'G', K => 'B', L => 'K', M => 'L', N => 'M', O => 'N', }; sub get_descendants { my ($tree, $node) = @_; my @children; for my $k (keys %$tree) { push @children, $k if $tree->{$k} eq $node; } return \@children; } my @paths = NestedLoops( [ sub { get_descendants($tree,'') }, (sub { get_descendants($tree,$_) } ) x (scalar(keys %$tree) - 2) ], { OnlyWhen => 1 }, sub { \@_ } ); print join(', ',@$_) . "\n" for (@paths); __END__ A A, B A, B, F A, B, K A, B, K, L A, B, K, L, M A, B, K, L, M, N A, B, K, L, M, N, O A, C A, C, E A, C, D A, C, D, H A, C, D, I A, C, D, G A, C, D, G, J