http://qs1969.pair.com?node_id=479155


in reply to Passing anon sub as param

The reason BrowserUk passed the node-printing code as an anonymous subroutine was to separate the traversal logic from the node-processing logic. With this separation, we can use the same traversal logic for other purposes, and we can use the same node-processing logic with other traversals.

Consider the following nested-array-style tree and logic to traverse it:

my $tree = [ 1 , [ 2 , 3 , [ 4 , [ 5 ] , 6 ] ] , 7 ] ; sub traverse { my ($nodefn, $tree, $depth) = @_; $depth ||= 0; $depth++; for (@$tree) { ref() ? traverse( $nodefn, $_, $depth ) : $nodefn->( $_, $depth ); } }
We can combine this traversal logic with task-specific node-processing logic. For example, to count the nodes in the tree, we might use logic like this:
sub count_nodes { my $count; traverse( sub { $count++ }, @_ ); $count; } print count_nodes($tree), $/; # 7
For other jobs we can easily "plug in" other node-processing code. Here is code to print a single indented node:
sub print_node { my ($leaf, $depth) = @_; print " " x ($depth - 1), "* $leaf", $/; }
We just plug it into traverse to print the tree's outline:
traverse( \&print_node, $tree ); # * 1 # * 2 # * 3 # * 4 # * 5 # * 6 # * 7
Going further, we can plug in new traversal logic, too. Here is logic to do a breadth-first traversal – all the leaves at each depth are processed before going deeper.
sub bfs_traverse { my ($nodefn, $tree, $depth) = @_; $depth ||= 0; $depth++; my @leaves = grep !ref(), @$tree; my @branches = grep ref(), @$tree; $nodefn->( $_, $depth ) for @leaves; bfs_traverse( $nodefn, [map @$_, @branches], $depth ) if @branches; }
Now we can use this traversal logic with our existing print_node logic to outline the tree in breadth-first order:
bfs_traverse( \&print_node, $tree ); # * 1 # * 7 # * 2 # * 3 # * 4 # * 6 # * 5
By this point, I hope you can see the answer to your second question: by keeping traversal and node-processing concerns separated and by combining them through a well-defined interface (here, function passing), we can mix and match logic. If we want a breadth-first outline, we don't need to write a breadth-first outline function; we can just combine a breadth-first traversal with a node-printing processor.

Cheers,
Tom