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 time 
do { say "Heads I win, tails I die."Bool.pick } or diesay "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 { 42.say };

...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 $f = "."say do { $f ~= "." } X~ 123;

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:

3do if 1 { 2 }  ; # OUTPUT: «(3, 2)␤» 
3,   (if 1 { 2 }) ; # OUTPUT: «(3, 2)␤» 
3,    if 1 { 2 }  ; # 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 $counter = 0;
my $result = do for ^5 { $counter++ };
say $counter# OUTPUT: «5␤» 
say $result;  # 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.