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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
=pod
=encoding utf-8
=head1 PURPOSE
Various tests of named and anonymous functions closing over variables.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2013-2014, 2017 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
use strict;
use warnings;
use Test::More;
use Test::Fatal;
my $x;
BEGIN { $x = 1 };
package Foo {
use Kavorka;
method new ($class: ...) {
bless {}, $class;
}
method inc { ++$x }
method dec { --$x }
}
subtest "Two functions closing over the same variable" => sub
{
my $foo = Foo->new;
is($x, 1);
is($foo->inc, 2);
is($foo->inc, 3);
is($x, 3);
is($foo->dec, 2);
is($foo->dec, 1);
is($x, 1);
};
package Goo {
use Kavorka;
method xyz {
my @links;
fun my $xxx { push @links, 42 };
$xxx->();
return \@links;
}
}
subtest "Closing over a variable in a lexical function" => sub
{
is_deeply(Goo->xyz, [42]);
is_deeply(Goo->xyz, [42]);
is_deeply(Goo->xyz, [42]);
};
package Hoo {
use Kavorka;
method xyz ($closeme) {
my $f = fun ($vvv = $closeme) { $vvv };
return (\$closeme, $f);
}
}
subtest "Closing over a variable in a default" => sub
{
my ($X1, $fourtytwo) = Hoo->xyz(42);
is($fourtytwo->(666), 666);
is($fourtytwo->(), 42);
my ($X2, $sixsixsix) = Hoo->xyz(666);
is($sixsixsix->(999), 999);
is($sixsixsix->(), 666);
$$X2 = 777;
is($sixsixsix->(), 777);
};
package Ioo {
use Kavorka;
method get_limit ($limit) {
fun (Int $x where { $_ < $limit }) { 1 };
}
}
subtest "Closing over a variable in a where {} block" => sub
{
my $lim7 = Ioo->get_limit(7);
ok $lim7->(6);
ok exception { $lim7->(8) };
my $lim12 = Ioo->get_limit(12);
ok $lim12->(8);
ok exception { $lim12->(14) };
ok $lim7->(6);
ok exception { $lim7->(8) };
};
package Joo {
use Kavorka;
method get_set ($x) {
return (
fun () { $x },
fun ($y) { $x = $y },
);
}
}
subtest "Two anonymous functions closing over the same variable" => sub
{
my ($g, $s) = Joo->get_set(20);
my ($g2, $s2) = Joo->get_set(666);
is($g->(), 20);
is($s->(21), 21);
is($g->(), 21);
is($s->($g->() * 2), 42);
is($g->(), 42);
is($g2->(), 666);
};
done_testing;
|