syntax do
Documentation for syntax do
assembled from the following types:
language documentation Control flow
From Control flow
(Control flow) control flow do 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
language documentation Statement prefixes
From Statement prefixes
(Statement prefixes) do (statement prefix) do
do
can be used as an statement prefix to disambiguate the statement they precede; this is needed, for instance, if you want to assign the result of a for
statement. A bare for
will fail, but this will work:
my = 0;my = do for ^5 ;say ; # OUTPUT: «5»say ; # OUTPUT: «(0 1 2 3 4)»
do
is equivalent, as in other cases, to surrounding a statement with a parenthesis. It can be used as an alternative with a (possibly more) straightforward syntax.