Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
Re: Passing anon sub as paramby tmoertel (Chaplain) |
on Jul 28, 2005 at 22:21 UTC ( [id://479155]=note: print w/replies, xml ) | Need Help?? |
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: 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: For other jobs we can easily "plug in" other node-processing code. Here is code to print a single indented node: We just plug it into traverse to print the tree's outline: 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. Now we can use this traversal logic with our existing print_node logic to outline the tree in breadth-first order: 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 Moertel : Blog / Talks / CPAN / LectroTest / PXSL / Coffee / Movie Rating Decoder
In Section
Seekers of Perl Wisdom
|
|