This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Introduce a new keyword, state, for state variables.
[perl5.git] / t / op / state.t
CommitLineData
952306ac
RGS
1#!./perl -w
2
3BEGIN {
4 chdir 't' if -d 't';
5 @INC = '../lib';
6 require './test.pl';
7}
8
9use strict;
10
11plan tests => 19;
12
13ok( ! defined state $uninit, q(state vars are undef by default) );
14
15sub stateful {
16 state $x;
17 state $y = 1;
18 my $z = 2;
19 return ($x++, $y++, $z++);
20}
21
22my ($x, $y, $z) = stateful();
23is( $x, 0, 'uninitialized state var' );
24is( $y, 1, 'initialized state var' );
25is( $z, 2, 'lexical' );
26
27($x, $y, $z) = stateful();
28is( $x, 1, 'incremented state var' );
29is( $y, 2, 'incremented state var' );
30is( $z, 2, 'reinitialized lexical' );
31
32($x, $y, $z) = stateful();
33is( $x, 2, 'incremented state var' );
34is( $y, 3, 'incremented state var' );
35is( $z, 2, 'reinitialized lexical' );
36
37sub nesting {
38 state $foo = 10;
39 my $t;
40 { state $bar = 12; $t = ++$bar }
41 ++$foo;
42 return ($foo, $t);
43}
44
45($x, $y) = nesting();
46is( $x, 11, 'outer state var' );
47is( $y, 13, 'inner state var' );
48
49($x, $y) = nesting();
50is( $x, 12, 'outer state var' );
51is( $y, 14, 'inner state var' );
52
53sub generator {
54 my $outer;
55 # we use $outer to generate a closure
56 sub { ++$outer; ++state $x }
57}
58
59my $f1 = generator();
60is( $f1->(), 1, 'generator 1' );
61is( $f1->(), 2, 'generator 1' );
62my $f2 = generator();
63is( $f2->(), 1, 'generator 2' );
64is( $f1->(), 3, 'generator 1 again' );
65is( $f2->(), 2, 'generator 2 once more' );