my %nodes = (); foreach my $tuple (split ',', $s) { # shorter spliting my ($child, $parent) = split ' ', $tuple; # init nodes if not already done $nodes{$child} ||= { node => $child, children => []}; $nodes{$parent} ||= { node => $parent, children => []}; # insert relationship push @{$nodes{$parent}{children}}, \$nodes{$child} $nodes{$child}{parent} = $parent; }