# This is a .pm just to (try to) make some CPAN document converters
# convert it happily as part of the dist's documentation tree.
package HTML::Element::traverse;
# Time-stamp: "2002-11-22 23:53:39 MST"
use HTML::Element ();
$VERSION = $VERSION = $HTML::Element::VERSION;
1;
__END__
=head1 NAME
HTML::Element::traverse - discussion of HTML::Element's traverse method
=head1 SYNOPSIS
# $element->traverse is unnecessary and obscure.
# Don't use it in new code.
=head1 DESCRIPTION
C<HTML::Element> provides a method C<traverse> that traverses the tree
and calls user-specified callbacks for each node, in pre- or
post-order. However, use of the method is quite superfluous: if you
want to recursively visit every node in the tree, it's almost always
simpler to write a subroutine does just that, than it is to bundle up
the pre- and/or post-order code in callbacks for the C<traverse>
method.
=head1 EXAMPLES
Suppose you want to traverse at/under a node $tree and give elements
an 'id' attribute unless they already have one.
You can use the C<traverse> method:
{
my $counter = 'x0000';
$start_node->traverse(
[ # Callbacks;
# pre-order callback:
sub {
my $x = $_[0];
$x->attr('id', $counter++) unless defined $x->attr('id');
return HTML::Element::OK; # keep traversing
},
# post-order callback:
undef
],
1, # don't call the callbacks for text nodes
);
}
or you can just be simple and clear (and not have to understand the
calling format for C<traverse>) by writing a sub that traverses the
tree by just calling itself:
{
my $counter = 'x0000';
sub give_id {
my $x = $_[0];
$x->attr('id', $counter++) unless defined $x->attr('id');
foreach my $c ($x->content_list) {
give_id($c) if ref $c; # ignore text nodes
}
};
give_id($start_node);
}
See, isn't that nice and clear?
But, if you really need to know:
=head1 THE TRAVERSE METHOD
The C<traverse()> method is a general object-method for traversing a
tree or subtree and calling user-specified callbacks. It accepts the
following syntaxes:
=over
=item $h->traverse(\&callback)
=item or $h->traverse(\&callback, $ignore_text)
=item or $h->traverse( [\&pre_callback,\&post_callback] , $ignore_text)
=back
These all mean to traverse the element and all of its children. That
is, this method starts at node $h, "pre-order visits" $h, traverses its
children, and then will "post-order visit" $h. "Visiting" means that
the callback routine is called, with these arguments:
$_[0] : the node (element or text segment),
$_[1] : a startflag, and
$_[2] : the depth
If the $ignore_text parameter is given and true, then the pre-order
=1= |