Skip to content

Commit fd36986

Browse files
committed
document Block
1 parent d510e13 commit fd36986

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

lib/Block.pod

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
=begin pod
2+
3+
=TITLE class Block
4+
5+
class Block is Code { }
6+
7+
A C<Block> is a code object meant for small-scale code reuse. A block is
8+
created syntactically by a list of statements enclosed in curly brackets.
9+
10+
Without an explicit signature or placeholder arguments, a block has C<$_>
11+
as a positional argument
12+
13+
my $block = { uc $_; };
14+
say $block.WHAT; # Block
15+
say $block('hello'); # HELLO
16+
17+
A block can have a signature between C<< -> >> or C<< <-> >> and the block:
18+
19+
my $add = -> $a, $b { $a + $b };
20+
say $add(38, 4); # 42
21+
22+
If the signature is introduced with C<< <-> >>, then the parameters are marked
23+
as C<rw> by default:
24+
25+
my $swap = <-> $a, $b { ($a, $b) = ($b, $a) };
26+
27+
my ($a, $b) = (2, 4);
28+
$swap($a, $b);
29+
say $a; # 4
30+
31+
Blocks that aren't of type C<Routine> (which is a subclass of C<Block>) are
32+
transparent to L<return>.
33+
34+
sub f() {
35+
say <a b c>.map: { return 42 };
36+
# ^^^^^^ exits &f, not just the block
37+
}
38+
39+
Bare blocks in sink context are automatically executed:
40+
41+
say 1;
42+
{
43+
say 2; # executed directly, not a Block object
44+
}
45+
say 3;
46+
47+
=end pod

0 commit comments

Comments
 (0)