Control flow

do — everything is an expression

Full

Turn a block or a control structure into a value with do.

In Raku almost everything is an expression that yields a value. do makes that explicit: it runs a block — or an if, for, given — and returns its result, so you can assign or pass it.

do a block #

do { … } runs the block and returns its last expression.

my $x = do { my $a = 5; $a * 2 }
say $x;
Output
10

do a conditional #

do if … else … turns a two-way branch into a value — an alternative to the ternary when the branches are blocks.

my $y = do if 3 > 2 { "yes" } else { "no" }
say $y;
Output
yes

do a loop #

do for collects the value of each iteration into a list.

say do for 1..3 { $_ * $_ }
Output
(1 4 9)

Notes #