use strict; use warnings; use Data::Dump::Streamer; my $s = "f b, b c, a c, e b, d a, g a"; my %children = map {split ' ', $_} split ',', $s; my %tree; # Build the tree push @{$tree{$children{$_}}}, $_ for keys %children; # Find the root my $root = (keys %children)[0]; while ($root) { last unless exists $children{$root}; $root = $children{$root}; } print "Root is $root\n"; Dump (\%tree);