Creating and using iterators
Iterators are a powerful technique that provide data on demand and avoid manual counters. These are functions that return the next element of some sequence each time you call it. In the previous section, we already created the iterator new-counter
, which generates incrementing integer numbers. Let us make something more complex:
sub make-iter(@data) { my $index = 0; sub { return @data[$index++]; } } my &iter = make-iter(<red green blue orange>); say iter; # red say iter; # green say iter; # blue say iter; # orange
The make-iter
function gets an array, installs the $index
position to zero and returns a sub that will be used as an iterator. Next time the iter
object is called, it returns the value at the current position and moves the internal pointer to the next element. After the data is exhausted, Nil
will be returned.
Iterators can also generate sequences according to certain rules. For example, here is an iterator that returns...