@@ -95,11 +95,31 @@ build an iterator type to be returned, such as we did in the previous example;
95
95
however, this example shows the minimal code needed to build a class that
96
96
fulfills the two iter(ator|able) roles.
97
97
98
-
99
-
100
98
= head1 How to iterate: contextualizing and topic variables
101
99
102
- TBD
100
+ C < for > and other loops place the item produced in every iteration into the
101
+ L < topic variable C < $_ > |/language/variables#index-entry-topic_variable > , or
102
+ capture them into the variables that are declared along with the block. These
103
+ variables can be directly used inside the loop, without needing to declare them,
104
+ by using the
105
+ L < C < ^ > twigil|https://docs.perl6.org/syntax/$CIRCUMFLEX_ACCENT#(Traps_to_avoid)_twigil_^> .
106
+
107
+ Implicit iteration occurs when using the L < sequence operator|/language/operators#index-entry-..._operators > .
108
+
109
+ say 1,1,1, { $^a²+2*$^b+$^c } … * > 300; # OUTPUT: «(1 1 1 4 7 16 46 127 475)
110
+
111
+ The generating block is being run once while the condition to finish the
112
+ sequence, in this case the term being bigger than 300, is not met. This has the
113
+ side effect of running a loop, but also creating a list that is output.
114
+
115
+ This can be done more systematically through the use of the L < C < gather/take >
116
+ blocks|/syntax/gather take > , which are a different kind of iterating construct
117
+ that instead of running in sink context, returns an item every iteration. This
118
+ <Advent Calendar
119
+ tutorial|https://perl6advent.wordpress.com/2009/12/23/day-23-lazy-fruits-from-the-gather-of-eden/>
120
+ explains use cases for this kind of loops; in fact, gather is not so much a
121
+ looping construct, but a statement prefix that collects the items produced by
122
+ C < take > and creates a list out of them.
103
123
104
124
= head1 C < Classic > loops and why we do not like them
105
125
0 commit comments