more useful options | |
PerlMonks |
A Filtering Iteratorby jdporter (Paladin) |
on Jul 21, 2008 at 16:37 UTC ( [id://699079]=CUFP: print w/replies, xml ) | Need Help?? |
I present here an iterator which applies filtering to some other iterator. You give it an iterator and a condition; it returns an iterator which produces the same sequence of values as the iterator you gave would, except those values which don't meet the condition are not returned, they are skipped. This iterator conforms to the interface of Iterator, except that the value method can return lists of values, not just single scalars. Besides new, it implements reset, value, and is_exhausted. The iterator you pass in should similarly implement the interface of Iterator. This "inner iterator" must implement methods reset, value, and is_exhausted. Again, its value method can return multiple values or a single value. The condition is defined as a subroutine, passed by reference. It will receive in @_ the value(s) returned by each call to the inner iterator's value method. It should return a boolean value. This will be used to determine whether that value will be returned by the outer iterator (the one created by this class). Let's look at the code:
Here's a sample application. The inner iterator returns the values in a given array, containing the integers 1 to 10. The condition returns true for those numbers which are odd. (Note that the inner iterator is created using the Iterator::Array class presented in Using Nested Iterators to find a Cross Product.)
Between the mind which plans and the hands which build, there must be a mediator... and this mediator must be the heart.
Back to
Cool Uses for Perl
|
|