-
Notifications
You must be signed in to change notification settings - Fork 292
/
Block.pod6
57 lines (38 loc) · 1.57 KB
/
Block.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
=begin pod
=TITLE class Block
=SUBTITLE Code object with its own lexical scope
class Block is Code { }
A C<Block> is a code object meant for small-scale code reuse. A block is
created syntactically by a list of statements enclosed in curly braces.
Without an explicit signature or placeholder arguments, a block has C<$_>
as a positional argument
my $block = { uc $_; };
say $block.^name; # OUTPUT: «Block»
say $block('hello'); # OUTPUT: «HELLO»
A block can have a L<Signature|/type/Signature> between C<< -> >> or C<< <-> >>
and the block:
my $add = -> $a, $b = 2 { $a + $b };
say $add(40); # OUTPUT: «42»
If the signature is introduced with C<< <-> >>, then the parameters are marked
as C<rw> by default:
X«|<->»
my $swap = <-> $a, $b { ($a, $b) = ($b, $a) };
my ($a, $b) = (2, 4);
$swap($a, $b);
say $a; # OUTPUT: «4»
Blocks that aren't of type C<Routine> (which is a subclass of C<Block>) are
transparent to L<return|/syntax/return>.
sub f() {
say <a b c>.map: { return 42 };
# ^^^^^^ exits &f, not just the block
}
The last statement is the implicit return value of the block.
say {1}.(); # OUTPUT: «1»
Bare blocks are automatically executed in the order they appear:
say 1; # OUTPUT: «1»
{
say 2; # OUTPUT: «2»; executed directly, not a Block object
}
say 3; # OUTPUT: «3»
=end pod
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6