In Control flow§

See primary documentation in context for Blocks

Like many other languages, Raku uses blocks enclosed by { and } to turn a sequence of statements into a Block that acts as a single one. It is OK to omit the semicolon between the last statement in a block and the closing }.

{ say "Hello"say "World" }

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␤» 
{ say 2say 3 };         # OUTPUT: «2␤3␤» 
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";
{ say "then here." };
{ say "not here"0} 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 Raku 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 
{ 42.say }                # OUTPUT: «42␤» 
{ 43.say }                # OUTPUT: «43␤» 
{ 42.say }{ 43.say }    # OUTPUT: «42␤43␤»

...but:

{ 42.say }  { 43.say }    # Syntax error 
{ 42.say} { 43.say }    # Also a syntax error, of course 

So, be careful when you backspace in a line-wrapping editor:

{ "Without semicolons line-wrapping can be a bit treacherous.".say } \
{ 43.say } # 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.

class C {
    say "I live";
    die "I will never live!"
};
my $c = C.new;                              │
# OUTPUT: Fails and writes «I live␤I will never live!␤ 

This block will first run the first statement, and then die printing the second statement. $c will never get a value.