September 2017
Beginner
402 pages
9h 52m
English
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; # redsay iter; # greensay iter; # bluesay 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 ...
Read now
Unlock full access