-
Notifications
You must be signed in to change notification settings - Fork 135
/
with-closure.t
56 lines (43 loc) · 1.96 KB
/
with-closure.t
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
use Test;
plan 18;
# L<S05/Transliteration/"If the right side of the arrow is a closure">
my $x = 0;
is 'aXbXcXd'.trans('X' => { ++$x }), 'a1b2c3d', 'Can use a closure on the RHS';
is $x, 3, 'Closure executed three times';
$x = 0;
is 'aXbXcX'.trans(:c, 'X' => { ++$x }), '1X2X3X', 'Can use a closure on the RHS with :c';
is $x, 3, 'Closure executed three times with :c';
$x = 0;
my $y = 0;
my $s = 'aXbYcYdX';
my %matcher = (
X => { ++$x },
Y => { ++$y },
);
is $s.trans(%matcher.pairs), 'a1b1c2d2', 'Can use two closures in trans';
is $s, 'aXbYcYdX', 'Source string unchanged';
is $s.trans([<X Y>] => [{++$x},{++$y}]), 'a3b3c4d4', 'can use closures in pairs of arrays';
is $s, 'aXbYcYdX', 'Source string unchanged';
$x = 0;
$y = 0;
my $s2 = 'ABC111DEF111GHI';
is $s2.trans([<1 111>] => [{++$x},{++$y}]), 'ABC1DEF2GHI', 'can use closures in pairs of arrays';
is $s2, 'ABC111DEF111GHI', 'Source string unchanged';
is $x, 0, 'Closure not invoked (only longest match used)';
is $y, 2, 'Closure invoked twice (once per replacement)';
{
# combined regex / closure
my $count = 0;
is 'hello'.trans(/l/ => { ++$count }), 'he12o', 'regex and closure mix';
#?rakudo todo 'nom regression'
is 'hello'.trans(/l/ => { $_ x 2 }), 'hellllo', 'regex and closure mix (with $/ as topic)';
my $x = 'hello';
#?rakudo todo 'nom regression'
is $x.trans(/(l)/ => { $_[0] x 2 }), 'hellllo', 'regex and closure mix (with $/ as topic and capture)';
is $x, 'hello', 'Original string not modified';
}
my $orig = 'hello';
#?rakudo skip 'Unable to resolve method ord in class Any'
is $orig.trans(/(l)/ => { $_[0].ord }), 'he108108o', 'capturing regex + closure with .ord on $_';
is $orig, 'hello', 'original string unchanged';
# vim: expandtab shiftwidth=4