Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Start documenting control flow statements
  • Loading branch information
Paul Cochrane committed Apr 8, 2015
1 parent ab324ed commit fa50342
Showing 1 changed file with 124 additions and 0 deletions.
124 changes: 124 additions & 0 deletions lib/Language/control.pod
@@ -0,0 +1,124 @@
=begin pod
=TITLE Control Flow
=SUBTITLE Statements used to control the flow of execution
=begin comment
=head2 do
=head2 if/elsif/else
=head2 for
=head2 gather/take
=end comment
=head2 given/when/default
The C<given> statement is Perl 6's topicalizing keyword in the same way that
C<switch> topicalizes in languages such as C. The keyword for individual
cases is C<when> and C<default> for the default case. In general this form
of control flow statement is written thus:
given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}
The C<when> expressions C<EXPR> are smart matched against the given value
such that it is possible to check against values, regular expressions, and
types when specifying a match
given 42 {
when Int { .say }
default { say "how did I get here?" }
}
#-> 42
In this form, the C<given>/C<when> construct acts much like a set of
C<if>/C<elsif>/C<else> statements. Thus it is necessary to be careful with the order of the C<when> statements. Hence the following code won't match with the value C<42>:
given 42 {
when Int { say "Int" }
when 42 { say 42 }
default { say "huh?" }
}
#-> Int
To get around this issue, one can use the C<proceed> and C<succeed>
statements. C<proceed> will match once more after a successful match, like so:
given 42 {
when Int { say "Int"; proceed }
when 42 { say 42 }
when 40..* { say "greater than 40" }
default { say "huh?" }
}
# -> Int
# -> 42
Note that the C<when 40..*> match didn't occur. For this to match such cases as
well, one would need a proceed in the C<when 42> block.
To make it clearer that C<proceed> doesn't merely attempt to match the
directly following block, however will attempt to match the C<given> value
once more, consider this code:
given 42 {
when Int { "Int".say; proceed }
when 43 { 43.say }
when 42 { 42.say }
default { "got change for an existential answer?".say }
}
#-> Int
#-> 42
which matches the C<Int>, skips C<43> since the value doesn't match, matches
C<42> since this is the next positive match, but doesn't enter the
C<default> block since the C<when 42> block doesn't contain a C<proceeds>.
By contrast, the C<succeed> keyword shortcircuits execution and exits the
C<given> block at that point.
given 42 {
when Int {
say "Int";
succeed;
say "never this!";
}
when 42 { say 42 }
default { say "dunno?" }
}
#-> Int
=begin comment
=head2 loop
=head2 repeat/while
=head2 repeat/until
=head2 unless
=head2 while
=head2 return
=head2 next
=head2 last
=head2 redo
=head2 goto
=end comment
=end pod

# vim: expandtab shiftwidth=4 ft=perl6

0 comments on commit fa50342

Please sign in to comment.