Control flow
Statements used to control the flow of execution
statements
Perl 6 programs consist of one or more statements. Simple statements are separated by semicolons. The following program will say "Hello" and then say "World" on the next line.
say "Hello";say "World";
In most places where spaces appear in a statement, and before the semicolon, it may be split up over many lines. Also, multiple statements may appear on the same line. It would be awkward, but the above example could also be written as:
say"Hello"; say "World";
Blocks
Like many other languages, Perl 6 uses blocks
enclosed by {
and }
to turn a sequence of statements into a single one. It is OK to skip the semicolon between the last statement in a block and the closing }
.
When a block stands alone as a statement, it will be entered immediately after the previous statement finishes, and the statements inside it will be executed.
say 1; # OUTPUT: «1»; # OUTPUT: «23»say 4; # OUTPUT: «4»
Unless it stands alone as a statement, a block simply creates a closure. The statements inside are not executed immediately. Closures are another topic and how they are used is explained elsewhere. For now it is just important to understand when blocks run and when they do not:
say "We get here"; ; or die;
In the above example, after running the first statement, the first block stands alone as a second statement, so we run the statement inside it. The second block is a closure, so instead, it makes an object of type Block
but does not run it. Object instances are usually considered to be true, so the code does not die, even though that block would evaluate to 0, were it to be executed. The example does not say what to do with the Block
object, so it just gets thrown away.
Most of the flow control constructs covered below are just ways to tell Perl 6 when, how, and how many times, to enter blocks like that second block.
Before we go into those, an important side-note on syntax: If there is nothing (or nothing but comments) on a line after a closing curly brace where you would normally put semicolon, then you do not need the semicolon:
# All three of these lines can appear as a group, as is, in a program# OUTPUT: «42»# OUTPUT: «43»; # OUTPUT: «4243»
...but:
# Syntax error# Also a syntax error, of course
So, be careful when you backspace in a line-wrapping editor:
\# Syntax error
You have to watch out for this in most languages anyway to prevent things from getting accidentally commented out. Many of the examples below may have unnecessary semicolons for clarity.
Class bodies behave like simple blocks for any top level expression; same goes to roles and other packages, like grammars (which are actually classes) or modules.
;my = C.new; │# OUTPUT: Fails and writes «I liveI will never live!
This block will first run the first statement, and then die
printing the second statement. $c
will never get a value.
Phasers
Blocks may have phasers: special labeled blocks that break their execution into phases that run in particular phases. See the page phasers for the details.
do
The simplest way to run a block where it cannot be a stand-alone statement is by writing do
before it:
# This dies half of the timedo or die; say "I win.";
Note that you need a space between the do
and the block.
The whole do {...}
evaluates to the final value of the block. The block will be run when that value is needed in order to evaluate the rest of the expression. So:
False and do ;
...will not say 42. However, the block is only evaluated once each time the expression it is contained in is evaluated:
# This says "(..1 ..2 ..3)" not "(..1 ...2 ....3)"my = "."; say do X~ 1, 2, 3;
In other words, it follows the same reification rules as everything else.
Technically, do
is a loop which runs exactly one iteration.
A do
may also be used on a bare statement (without curly braces) but this is mainly just useful for avoiding the syntactical need to parenthesize a statement if it is the last thing in an expression:
3, do if 1 ; # OUTPUT: «(3, 2)»3, (if 1 ) ; # OUTPUT: «(3, 2)»
3, if 1 ; # Syntax error
start
The simplest way to run a block asynchronously is by writing start
before it:
startsay "working";# working, done
Note that you need a space between the start
and the block. In the example above, the start
block is in sink context, since it's not assigned to a variable. From version 6.d, these kind of blocks have an exception handler attached:
startsay "working";sleep 10;
This code will print Unhandled exception in code scheduled on thread 4 We're dead
in version 6.d, while it will simply get out after waiting for 10 seconds in version 6.c.
The start {...}
immediately returns a Promise
that can be safely ignored if you are not interested in the result of the block. If you are interested in the final value of the block, you can call the .result
method on the returned promise. So:
my = start# ... do other stuffsay "The result is $promise.result()";
If the code inside the block has not finished, the call to .result
will wait until it is done.
A start
may also be used on a bare statement (without curly braces). This is mainly useful when calling a subroutine / method on an object is the only thing to do asynchronously.
sub get42my = start get42;say .result; # OUTPUT: «42»
Note that code executed this way does not have access to the special variables $!
and $/
of its outer block, but receives new ones, so every asynchronous task has its per-task state.
Thus, try
expressions and regex matches executed in the asynchronous task have their per-task state.
'a' ~~ /a/; # $/ is set to 「a」try die; # $! is defined now with an anonymous AdHoc exception# as a code blockawait start ; # OUTPUT: «Nil»await start ; # OUTPUT: «Nil»# as a single statementawait start $!.say; # OUTPUT: «Nil»await start $/.say; # OUTPUT: «Nil»
if
To conditionally run a block of code, use an if
followed by a condition. The condition, an expression, will be evaluated immediately after the statement before the if
finishes. The block attached to the condition will only be evaluated if the condition means True
when coerced to Bool
. Unlike some languages the condition does not have to be parenthesized, instead the {
and }
around the block are mandatory:
if 1 ; # says "1 is true"
if 1 "1 is true".say ; # syntax error, missing block
if 0 ; # does not say anything, because 0 is false
if 42.say and 0 ; # says "42" but does not say "43"
There is also a form of if
called a "statement modifier" form. In this case, the if and then the condition come after the code you want to run conditionally. Do note that the condition is still always evaluated first:
43.say if 42.say and 0; # says "42" but does not say "43"43.say if 42.say and 1; # says "42" and then says "43"say "It is easier to read code when 'if's are kept on left of screen"if True; # says the above, because it is trueif True; # says "43" as well
The statement modifier form is probably best used sparingly.
The if
statement itself will either slip us an empty list, if it does not run the block, or it will return the value which the block produces:
my = 0; say (1, (if 0 ), 3, ); # says "(1 3 0)"my = 0; say (1, (if 1 ), 3, ); # says "(1 2 3 42)"say (1, (if 1 ), 3); # does not slip, says "(1 (2 2) 3)"
For the statement modifier it is the same, except you have the value of the statement instead of a block:
say (1, (42 if True) , 2); # says "(1 42 2)"say (1, (42 if False), 2); # says "(1 2)"say (1, 42 if False , 2); # says "(1 42)" because "if False, 2" is true
The if
does not change the topic ($_
) by default. In order to access the value which the conditional expression produced, you have to ask for it more strongly:
= 1; if 42 ; # says "1"= 1; if 42 -> ; # says "42"= 1; if 42 -> ; # says "1" then says "42"= 1; if 42 ; # says "1" then says "42"
else/elsif
A compound conditional may be produced by following an if
conditional with else
to provide an alternative block to run when the conditional expression is false:
if 0 else ; # says "yes"if 0 else ; # says "yes", space is not required
The else
cannot be separated from the conditional statement by a semicolon, but as a special case, it is OK to have a newline.
if 0 ; else ; # syntax error
if 0else ; # says "yes"
Additional conditions may be sandwiched between the if
and the else
using elsif
. An extra condition will only be evaluated if all the conditions before it were false, and only the block next to the first true condition will be run. You can end with an elsif
instead of an else
if you want.
if 0 elsif False else # says "yes"if 0 elsif True else # says "YES"if 0 elsif False # does not say anythingsub rightsub wrongif wrong() elsif right() else# The above says "Wrong!" then says "Right!" then says "yes"
You cannot use the statement modifier form with else
or elsif
:
42.say if 0 else # syntax error
All the same rules for semicolons and newlines apply, consistently
if 0 ; elsif 1 else ; # syntax errorif 0 elsif 1 ; else ; # syntax error
if 0 elsif 1 else ; # says "1"
if 0 elsif 1else ; # says "1"if 0elsif 1 else ; # says "1"if 0elsif Falseelse ; # says "yes"
The whole thing either slips us an empty list (if no blocks were run) or returns the value produced by the block that did run:
my = 0; say (1,(if 0 elsif False ),3, ); # says "(1 3 0)"my = 0; say (1,(if 0 else ),3, ); # says "(1 2 3 43)"
It's possible to obtain the value of the previous expression inside an else
, which could be from if
or the last elsif
if any are present:
= 1; if 0 else -> ; # says "1 0"= 1; if False else -> ; # says "1 False"if False elsif 0 else -> ; # says "0"
unless
When you get sick of typing "if not (X)" you may use unless
to invert the sense of a conditional statement. You cannot use else
or elsif
with unless
because that ends up getting confusing. Other than those two differences unless
works the same as if:
unless 1 ; # does not say anything, since 1 is true
unless 1 "1 is false".say ; # syntax error, missing block
unless 0 ; # says "0 is false"
unless 42.say and 1 ; # says "42" but does not say "43"43.say unless 42.say and 0; # says "42" and then says "43"43.say unless 42.say and 1; # says "42" but does not say "43"= 1; unless 0 ; # says "1"= 1; unless 0 -> ; # says "0"= 1; unless False -> ; # says "False"my = 0; say (1, (unless 0 ), 3, ); # says "(1 2 3 42)"my = 0; say (1, (unless 1 ), 3, ); # says "(1 3 0)"
with orwith without
The with
statement is like if
, but tests for definedness rather than truth, and it topicalizes on the condition, much like given
:
with "abc".index("a") # prints 0
Similarly to elsif
, orwith
may be used to chain definedness tests:
# The below code says "Found a at 0"my = "abc";with .index("a")orwith .index("b")orwith .index("c")else
You may intermix if
-based and with
-based clauses.
# This says "Yes"if 0 orwith Nil orwith 0 ;
As with unless
, you may use without
to check for undefinedness, but you may not add an else
clause:
my = Any;without
There are also with
and without
statement modifiers:
my = (Any, True).roll;say 42 with ;warn "undefined answer" without ;
As with the other chainable constructs, an else
completing a with/if
..orwith/elsif
chain will itself topicalize to the value of the prior (failed) condition's topic (either the topic of with
or the final orwith
or elsif
).
In the case of an else
following a with
or orwith
, topicalizing a value guaranteed to be undefined may seem useless. But it makes for a useful idiom when used in conjunction with operations that may fail, because Failure values are always undefined:
sub may_fail( --> Numeric )with may_fail() ->else
Note that while topicalizing a Failure marks it handled
—so you can use the with
/else
to proceed safely with execution—it doesn't make the Failure value itself safe. Even within the else
clause, if you try to use the value directly, it will result in your else
clause itself failing (or, in Rakudo, "promoting" the Failure into a thrown exception).
But as seen above, you can use the methods of a handled Failure
object the else
topicalizes, such as exception
, if you wish to provide diagnostics or interrogate the underlying Exception.
when
The when
block is similar to an if
block and either or both can be used in an outer block; they also both have a "statement modifier" form. But there is a difference in how following code in the same, outer block is handled: When the when
block is executed, control is passed to the enclosing block and following statements are ignored; but when the if
block is executed, following statements are executed. [1] The following examples should illustrate the if
or when
block's default behavior assuming no special exit or other side effect statements are included in the if
or when
blocks:
Should the if
and when
blocks above appear at file scope, following statements would be executed in each case.
There is one other feature when
has that if
doesn't: the when
's boolean context test defaults to $_ ~~
while the if
's does not. That has an effect on how one uses the X in the when
block without a value for $_
(it's Any
in that case and Any
smartmatches on True
: Any ~~ True
yields True
). Consider the following:
Finally, when
's statement modifier form does not affect execution of following statements either inside or outside of another block:
say "foo" when X; # if X is true statement is executed# following statements are not affected
Since a successful match will exit the block, the behavior of this piece of code:
= True;my ;;say ; # OUTPUT: «(Any)»
is explained since the do
block is abandoned before any value is stored or processed. However, in this case:
= False;my ;;say ; # OUTPUT: «False»
the block is not abandoned since the comparison is false, so $a
will actually get a value.
for
The for
loop iterates over a list, running the statements inside a block once on each iteration. If the block takes parameters, the elements of the list are provided as arguments.
my = 1..3;for # prints each value contained in @foofor # same thing, because .print implies a $_ argumentfor # prints 42 as many times as @foo has elements
Pointy block syntax or a placeholder may be used to name the parameter, of course.
my = 1..3;for ->for # same thing
Multiple parameters can be declared, in which case the iterator takes as many elements from the list as needed before running the block.
my = 1..3;for .kv -> ,my = <a b c> Z=> 1,2,3;for .kv -> ,for 1, 1.1, 2, 2.1 # says "1 < 1.1" then says "2 < 2.1"
Parameters of a pointy block can have default values, allowing to handle lists with missing elements.
my = 1,2,3,4;for -> , = 'N/A', = 'N/A'# OUTPUT: «1 2 34 N/A N/A»
If the postfix form of for
is used, a block is not required and the topic is set for the statement list.
say „I $_ butterflies!“ for <♥ ♥ ♥>;# OUTPUT«I ♥ butterflies!I ♥ butterflies!I ♥ butterflies!»
A for
may be used on lazy lists – it will only take elements from the list when they are needed, so to read a file line by line, you could use:
for .lines ->
Iteration variables are always lexical, so you don't need to use my
to give them the appropriate scope. Also, they are read-only aliases. If you need them to be read-write, use <->
instead of ->
. If you need to make $_
read-write in a for loop, do so explicitly.
my = 1..3;for <->
A for
loop can produce a List
of the values produced by each run of the attached block. To capture these values, put the for loop in parenthesis or assign them to an array:
(for 1, 2, 3 ).say; # OUTPUT «(2 4 6)»my = do for 1, 2, 3 ; .say; # OUTPUT «[2 4 6]»my = (for 1, 2, 3 ); .say; # OUTPUT: «[2 4 6]»
The Empty
constant will act as a no-op for a loop:
say "Not here" for Empty;
Will not do anything. This constant is equivalent to a empty Slip or List.
Undefined values will behave in the same way:
my := Empty;.say for ;say ; # OUTPUT: «()»
Assigning Empty
will effectively undefine an Array
, using for
over an undefined array will not even enter the loop, as shown, effectively behaving in the same way as above when Empty
was used directly.
With hyper
and race
, the for
loop is potentially iterated in parallel. See also the documentation for hyper
and race
in class Map.
my = hyper for ^10_000 -> ;say .elems; # OUTPUT: «1229»say .tail: 5; # OUTPUT: «(9931 9941 9949 9967 9973)»
with hyper
the order of elements is preserved.
my = race for ^10_000 -> ;say .elems; # OUTPUT: «1229»
Unlike hyper, race
does not preserve the order of elements.
gather/take
gather
is a statement or block prefix that returns a sequence of values. The values come from calls to take in the dynamic scope of the gather
block.
my = gathersay join ', ', ; # OUTPUT: «1, 5, 42»
gather/take
can generate values lazily, depending on context. If you want to force lazy evaluation use the lazy subroutine or method. Binding to a scalar or sigilless container will also force laziness.
For example
my = lazy gathersay [0];say 'between consumption of two values';say [1];# OUTPUT:# 1# between consumption of two values# Produced a value# 2
gather/take
is scoped dynamically, so you can call take
from subs or methods that are called from within gather
:
sub weird(, : = 'forward')say weird(<a b c>, :direction<backward> ); # OUTPUT: «(c b a)»
If values need to be mutable on the caller side, use take-rw.
Note that gather/take
also work for hashes. The return value is still a Seq
but the assignment to a hash in the following example makes it a hash.
my = gather ;say ; # OUTPUT: «{bar => 2, foo => 1}»
supply/emit
Emits the invocant into the enclosing supply:
my = supply.tap:# OUTPUT:# received Str (foo)# received Int (42)# received Rat (0.5)
given
The given
statement is Perl 6's topicalizing keyword in a similar way that switch
topicalizes in languages such as C. In other words, given
sets $_
inside the following block. The keywords for individual cases are when
and default
. The usual idiom looks like this:
my = (Any, 21, any <answer lie>).pick;given
The given
statement is often used alone:
given 42
This is a lot more understandable than:
(42)
default and when
A block containing a default
statement will be left immediately when the sub-block after the default
statement is left. It is as though the rest of the statements in the block are skipped.
given 42# The above block evaluates to 43
A when
statement will also do this (but a when
statement modifier will not.)
In addition, when
statements smartmatch
the topic ($_
) against a supplied expression such that it is possible to check against values, regular expressions, and types when specifying a match.
for 42, 43, "foo", 44, "bar"# OUTPUT: «4243Not an Int or a Bar44Bar»
In this form, the given
/when
construct acts much like a set of if
/elsif
/else
statements. Be careful with the order of the when
statements. The following code says "Int"
not 42
.
given 42# OUTPUT: «Int»
When a when
statement or default
statement causes the outer block to return, nesting when
or default
blocks do not count as the outer block, so you can nest these statements and still be in the same "switch" just so long as you do not open a new block:
given 42# OUTPUT: «42»
when
statements can smartmatch against Signatures.
proceed
succeed
Both proceed
and succeed
are meant to be used only from inside when
or default
blocks.
The proceed
statement will immediately leave the when
or default
block, skipping the rest of the statements, and resuming after the block. This prevents the when
or default
from exiting the outer block.
given *"This says".say;
This is most often used to enter multiple when
blocks. proceed
will resume matching after a successful match, like so:
given 42# OUTPUT: «Int»# OUTPUT: «42»
Note that the when 40..*
match didn't occur. For this to match such cases as well, one would need a proceed
in the when 42
block.
This is not like a C
switch
statement, because the proceed
does not merely enter the directly following block, it attempts to match the given
value once more, consider this code:
given 42# OUTPUT: «Int»# OUTPUT: «42»
...which matches the Int
, skips 43
since the value doesn't match, matches 42
since this is the next positive match, but doesn't enter the default
block since the when 42
block doesn't contain a proceed
.
By contrast, the succeed
keyword short-circuits execution and exits the entire given
block at that point. It may also take an argument to specify a final value for the block.
given 42# OUTPUT: «Int»
If you are not inside a when or default block, it is an error to try to use proceed
or succeed
.Also remember, the when
statement modifier form does not cause any blocks to be left, and any succeed
or proceed
in such a statement applies to the surrounding clause, if there is one:
given 42
given as a statement
given
can follow a statement to set the topic in the statement it follows.
.say given "foo";# OUTPUT: «foo»printf "%s %02i.%02i.%i",<Mo Tu We Th Fr Sa Su>[.day-of-week - 1],.day,.month,.yeargiven DateTime.now;# OUTPUT: «Sa 03.06.2016»
loop
The loop
statement takes three statements in parentheses separated by ;
that take the role of initializer, conditional and incrementer. The initializer is executed once and any variable declaration will spill into the surrounding block. The conditional is executed once per iteration and coerced to Bool
, if False
the loop is stopped. The incrementer is executed once per iteration.
loop (my = 0; < 10; ++)
The infinite loop does not require parentheses.
loop
The loop
statement may be used to produce values from the result of each run of the attached block if it appears in lists:
(loop ( my = 0; ++ < 3;) ).say; # OUTPUT: «(2 4 6)»my = (loop ( my = 0; ++ < 3;) ); .say; # OUTPUT: «[2 4 6]»my = do loop ( my = 0; ++ < 3;) ; .say; # same thing
Unlike a for
loop, one should not rely on whether returned values are produced lazily. It would probably be best to use eager
to guarantee that a loop whose return value may be used actually runs:
sub heads-in-a-row
while, until
The while
statement executes the block as long as its condition is true. So
my = 1;while < 4print "\n";# OUTPUT: «123»
Similarly, the until
statement executes the block as long as the expression is false.
my = 1;until > 3print "\n";# OUTPUT: «123»
The condition for while
or until
can be parenthesized, but there must be a space between the keyword and the opening parenthesis of the condition.
Both while
and until
can be used as statement modifiers. E. g.
my = 42;-- while > 12
Also see repeat/while
and repeat/until
below.
All these forms may produce a return value the same way loop
does.
repeat/while, repeat/until
Executes the block at least once and, if the condition allows, repeats that execution. This differs from while
/until
in that the condition is evaluated at the end of the loop, even if it appears at the front.
my = -42;repeatwhile < 5;.say; # OUTPUT: «5»repeatwhile < 5;.say; # OUTPUT: «6»repeat while < 10.say; # OUTPUT: «10»repeat while < 10.say; # OUTPUT: «11»repeatuntil >= 15;.say; # OUTPUT: «15»repeatuntil >= 15;.say; # OUTPUT: «16»repeat until >= 20.say; # OUTPUT: «20»repeat until >= 20.say; # OUTPUT: «21»
All these forms may produce a return value the same way loop
does.
return
The sub return
will stop execution of a subroutine or method, run all relevant phasers and provide the given return value to the caller. The default return value is Nil
. If a return type constraint is provided it will be checked unless the return value is Nil
. If the type check fails the exception X::TypeCheck::Return is thrown. If it passes a control exception is raised and can be caught with CONTROL.
Any return
in a block is tied to the first Routine
in the outer lexical scope of that block, no matter how deeply nested. Please note that a return
in the root of a package will fail at runtime. A return
in a block that is evaluated lazily (e.g. inside map
) may find the outer lexical routine gone by the time the block is executed. In almost any case last
is the better alternative. Please check the functions documentation for more information on how return values are handled and produced.
return-rw
The sub return
will return values, not containers. Those are immutable and will lead to runtime errors when attempted to be mutated.
sub s();say ++s();CATCH ;# OUTPUT: «X::Multi::NoMatch.new(dispatcher …
To return a mutable container, use return-rw
.
sub s();say ++s();# OUTPUT: «42»
The same rules as for return
regarding phasers and control exceptions apply.
fail
Leaves the current routine and returns the provided Exception or Str
wrapped inside a Failure, after all relevant phasers are executed. If the caller activated fatal exceptions via the pragma use fatal;
, the exception is thrown instead of being returned as a Failure
.
sub f ;say f;CATCH# OUTPUT: «X::AdHoc: WELP!»
once
A block prefix with once
will be executed exactly once, even if placed inside a loop or a recursive routine.
my = 3;loop# OUTPUT: «oncemanymanymany»
This works per "clone" of the containing code object, so:
( xx 3).map: ; # says 42 thrice
Note that this is not a thread-safe construct when the same clone of the same block is run by multiple threads. Also remember that methods only have one clone per class, not per object.
quietly
A quietly
block will suppress all warnings generated in it.
quietly ;warn 'still kaput!';# OUTPUT: «still kaput! [...]»
Any warning generated from any routine called from within the block will also be suppressed:
sub told-you ;quietly ;warn 'Only telling you now!'# OUTPUT: «Only telling you now! [...] »
LABELs
while
, until
, loop
and for
loops can all take a label, which can be used to identify them for next
, last
, and redo
. Nested loops are supported, for instance:
OUTAHERE: while True
Labels can be used also within nested loops to name each loop, for instance:
OUTAHERE:loop ( my = 1; True; ++ )
next
The next
command starts the next iteration of the loop. So the code
my = 1, 2, 3, 4, 5;for ->
prints "1245".
If the NEXT
phaser is present, it runs before the next iteration:
my Int = 0;while ( < 10)# OUTPUT: «1 is odd.3 is odd.5 is odd.7 is odd.9 is odd.»
In a whenever block, next
immediately exits the block for the current value:
react
prints "0", "1" and "4" - integers from 0 to 4 with primes skipped.
*Since version 6.d, the next
command in a loop that collects its last statement values returns Empty
for the iterations they run on.*
last
The last
command immediately exits the loop in question.
my = 1, 2, 3, 4, 5;for ->
prints "12".
If the LAST
phaser is present, it runs before exiting the loop:
my Int = 1;while ( < 10)# OUTPUT: «The last number was 5.»
*Since version 6.d, the last
command in a loop that collects its last statement values returns Empty
for the iterations they run on.*
redo
The redo
command restarts the loop block without evaluating the conditional again.
loop