sub is_circular { my $obj = shift; # Object to be traversed my $path = shift || []; # Check of $obj is in the $path foreach my $ancestor (@{$path}) { return 1 if $ancestor eq $obj; } # Check the children recursively, depth first # (My imaginary $obj conveniently has # a method for getting an array of its children) foreach my $child ($obj->children) { return 1 if is_circular($child, [ @{$path}, $obj ] ); } return 0; }