Skip to content

Commit d00b646

Browse files
committed
Continues with #2069, with iterating constructs
1 parent 35df3e1 commit d00b646

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

doc/Language/iterating.pod6

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,31 @@ build an iterator type to be returned, such as we did in the previous example;
9595
however, this example shows the minimal code needed to build a class that
9696
fulfills the two iter(ator|able) roles.
9797
98-
99-
10098
=head1 How to iterate: contextualizing and topic variables
10199
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.
103123
104124
=head1 C<Classic> loops and why we do not like them
105125

0 commit comments

Comments
 (0)