2 # tests state variables
15 ok( ! defined state $uninit, q(state vars are undef by default) );
23 return ($x++, $y++, $z++);
26 my ($x, $y, $z) = stateful();
27 is( $x, 0, 'uninitialized state var' );
28 is( $y, 1, 'initialized state var' );
29 is( $z, 2, 'lexical' );
31 ($x, $y, $z) = stateful();
32 is( $x, 1, 'incremented state var' );
33 is( $y, 2, 'incremented state var' );
34 is( $z, 2, 'reinitialized lexical' );
36 ($x, $y, $z) = stateful();
37 is( $x, 2, 'incremented state var' );
38 is( $y, 3, 'incremented state var' );
39 is( $z, 2, 'reinitialized lexical' );
46 { state $bar = 12; $t = ++$bar }
52 is( $x, 11, 'outer state var' );
53 is( $y, 13, 'inner state var' );
56 is( $x, 12, 'outer state var' );
57 is( $y, 14, 'inner state var' );
63 # we use $outer to generate a closure
64 sub { ++$outer; ++state $x }
68 is( $f1->(), 1, 'generator 1' );
69 is( $f1->(), 2, 'generator 1' );
71 is( $f2->(), 1, 'generator 2' );
72 is( $f1->(), 3, 'generator 1 again' );
73 is( $f2->(), 2, 'generator 2 once more' );
79 sub TIESCALAR {bless {}};
80 sub FETCH { ++$fetchcount; 18 };
81 tie my $y, "countfetches";
82 sub foo { state $x = $y; $x++ }
83 ::is( foo(), 18, "initialisation with tied variable" );
84 ::is( foo(), 19, "increments correctly" );
85 ::is( foo(), 20, "increments correctly, twice" );
86 ::is( $fetchcount, 1, "fetch only called once" );
89 # state variables are shared among closures
93 state $cash_in_store = 0;
95 add => sub { $cash_in_store += $amount },
96 del => sub { $cash_in_store -= $amount },
97 bal => sub { $cash_in_store },
101 gen_cashier(59)->{add}->();
102 gen_cashier(17)->{del}->();
103 is( gen_cashier()->{bal}->(), 42, '$42 in my drawer' );
105 # stateless assignment to a state variable
109 (state $reinitme, my $foo) = (42, 'bar');
112 is( stateless(), 43, 'stateless function, first time' );
113 is( stateless(), 43, 'stateless function, second time' );
123 my $xsize = stateful_array();
124 is( $xsize, 0, 'uninitialized state array' );
126 $xsize = stateful_array();
127 is( $xsize, 1, 'uninitialized state array after one iteration' );
136 my $xhval = stateful_hash();
137 is( $xhval, 0, 'uninitialized state hash' );
139 $xhval = stateful_hash();
140 is( $xhval, 1, 'uninitialized state hash after one iteration' );
142 # state declaration with a list
145 # note that this should be a state assignment, while (state $lager, state $stout) shouldn't
146 state($lager, $stout) = (11, 22);
152 my $ls = statelist();
153 is($ls, "12/23", 'list assignment to state scalars');
155 is($ls, "13/24", 'list assignment to state scalars');
158 state($sherry, $bourbon) = (1 .. 2);
165 is($ls, "2/3", 'list assignment to state scalars');
167 is($ls, "3/4", 'list assignment to state scalars');