Rules / Types, classes & roles / basic

Block Reference

Code object with its own lexical scope

What it is #

Position in the hierarchy #

Inherits from
Does
Inherited byRoutine

Examples, run three ways #

Every example below comes from the official documentation, together with the output that documentation asserts. Each was then executed by Rakudo and by Raku++ when this page was built. Where the three agree, one result is shown; where they do not, all three are — because which of them is wrong is exactly the information worth having.

2 no-output · 5 ok

class Block is Code { }

Not executed: the documentation states no expected output for this example.

my $block = { uc $_; };
say $block.^name;           # OUTPUT: «Block␤»
say $block('hello');        # OUTPUT: «HELLO␤»
say {;}.signature;          # OUTPUT: «(;; $_? is raw = OUTER::<$_>)␤»
Output
Block
HELLO
(;; $_? is raw = OUTER::<$_>)

Documentation, Rakudo and Raku++ all agree.

my $add = -> $a, $b = 2 { $a + $b };
say $add(40);               # OUTPUT: «42␤»
Output
42

Documentation, Rakudo and Raku++ all agree.

my $swap = <-> $a, $b { ($a, $b) = ($b, $a) };
my ($a, $b) = (2, 4);
$swap($a, $b);
say $a;                     # OUTPUT: «4␤»
Output
4

Documentation, Rakudo and Raku++ all agree.

sub f() {
    say <a b c>.map: { return 42 };
                   #   ^^^^^^   exits &f, not just the block
}

Not executed: the documentation states no expected output for this example.

say {1}.(); # OUTPUT: «1␤»
Output
1

Documentation, Rakudo and Raku++ all agree.

say 1;                # OUTPUT: «1␤»
{
    say 2;            # OUTPUT: «2␤»; executed directly, not a Block object
}
say 3;                # OUTPUT: «3␤»
Output
1
2
3

Documentation, Rakudo and Raku++ all agree.