Commit | Line | Data |
---|---|---|
952306ac RGS |
1 | #!./perl -w |
2 | ||
3 | BEGIN { | |
4 | chdir 't' if -d 't'; | |
5 | @INC = '../lib'; | |
6 | require './test.pl'; | |
7 | } | |
8 | ||
9 | use strict; | |
10 | ||
11 | plan tests => 19; | |
12 | ||
13 | ok( ! defined state $uninit, q(state vars are undef by default) ); | |
14 | ||
15 | sub stateful { | |
16 | state $x; | |
17 | state $y = 1; | |
18 | my $z = 2; | |
19 | return ($x++, $y++, $z++); | |
20 | } | |
21 | ||
22 | my ($x, $y, $z) = stateful(); | |
23 | is( $x, 0, 'uninitialized state var' ); | |
24 | is( $y, 1, 'initialized state var' ); | |
25 | is( $z, 2, 'lexical' ); | |
26 | ||
27 | ($x, $y, $z) = stateful(); | |
28 | is( $x, 1, 'incremented state var' ); | |
29 | is( $y, 2, 'incremented state var' ); | |
30 | is( $z, 2, 'reinitialized lexical' ); | |
31 | ||
32 | ($x, $y, $z) = stateful(); | |
33 | is( $x, 2, 'incremented state var' ); | |
34 | is( $y, 3, 'incremented state var' ); | |
35 | is( $z, 2, 'reinitialized lexical' ); | |
36 | ||
37 | sub 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(); | |
46 | is( $x, 11, 'outer state var' ); | |
47 | is( $y, 13, 'inner state var' ); | |
48 | ||
49 | ($x, $y) = nesting(); | |
50 | is( $x, 12, 'outer state var' ); | |
51 | is( $y, 14, 'inner state var' ); | |
52 | ||
53 | sub generator { | |
54 | my $outer; | |
55 | # we use $outer to generate a closure | |
56 | sub { ++$outer; ++state $x } | |
57 | } | |
58 | ||
59 | my $f1 = generator(); | |
60 | is( $f1->(), 1, 'generator 1' ); | |
61 | is( $f1->(), 2, 'generator 1' ); | |
62 | my $f2 = generator(); | |
63 | is( $f2->(), 1, 'generator 2' ); | |
64 | is( $f1->(), 3, 'generator 1 again' ); | |
65 | is( $f2->(), 2, 'generator 2 once more' ); |