in reply to tree with variable number of children

Weaknesses (in my mind):

I think you could do it much more efficiently with a hash. Something to the effect of:
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; }
Then you could walk up the tree to get the root and already have a built tree.

Update: your format is flexible enough to describe any directed graph. It is a reasonable expectation that code manipulating such data should halt for any acyclic input.