in reply to Inspecting each element in a tree, specifically HTML::Tree
The recursive example is quite a simple and good one. If you don't understand it then you should read up on the topic of recursion. It's quite a widely used concept in programming and it can make things that would otherwise be very hard to program, quite easy and concise. Developing a good understanding of what recursion is, how/why it works, and when it's a good idea to use it will help you not just solve your current problem, but become a better programmer.
Wikipedia has a reasonably good article on recursion.
If this helps, here's a slightly rewritten version of your recursive function:
sub do_something_recursively { my ($element) = @_; # Here we will do something just to $element # without worrying about recursion at all. $element->set_class("processed"); # Now we loop through each child element foreach my $child ($element->content_list) { # Skip text nodes next unless ref $child; # And we call *this function* on the child do_something_recursively($child); } } do_something_recursively($root_element);
|
|---|