summaryrefslogtreecommitdiff
path: root/t/op
diff options
context:
space:
mode:
authorRafael Garcia-Suarez <rgarciasuarez@gmail.com>2006-05-04 07:42:27 +0000
committerRafael Garcia-Suarez <rgarciasuarez@gmail.com>2006-05-04 07:42:27 +0000
commitea84231e9df32b276c544e7c6b0ab0b08050a7d9 (patch)
tree1da06eea5263b058c8fab83a2767edf2747c849c /t/op
parentaa2c63737286632915551d619f384bdece155a3f (diff)
downloadperl-ea84231e9df32b276c544e7c6b0ab0b08050a7d9.tar.gz
Another test for state variables and closures,
adapted from a Perl 6 example, pointed out by Joshua "Limbic_Region" Gatcomb p4raw-id: //depot/perl@28090
Diffstat (limited to 't/op')
-rw-r--r--t/op/state.t29
1 files changed, 27 insertions, 2 deletions
diff --git a/t/op/state.t b/t/op/state.t
index 6da247874e..7a82f8a440 100644
--- a/t/op/state.t
+++ b/t/op/state.t
@@ -1,4 +1,5 @@
#!./perl -w
+# tests state variables
BEGIN {
chdir 't' if -d 't';
@@ -9,10 +10,12 @@ BEGIN {
use strict;
use feature "state";
-plan tests => 25;
+plan tests => 26;
ok( ! defined state $uninit, q(state vars are undef by default) );
+# basic functionality
+
sub stateful {
state $x;
state $y = 1;
@@ -35,6 +38,8 @@ is( $x, 2, 'incremented state var' );
is( $y, 3, 'incremented state var' );
is( $z, 2, 'reinitialized lexical' );
+# in a nested block
+
sub nesting {
state $foo = 10;
my $t;
@@ -51,6 +56,8 @@ is( $y, 13, 'inner state var' );
is( $x, 12, 'outer state var' );
is( $y, 14, 'inner state var' );
+# in a closure
+
sub generator {
my $outer;
# we use $outer to generate a closure
@@ -65,6 +72,7 @@ is( $f2->(), 1, 'generator 2' );
is( $f1->(), 3, 'generator 1 again' );
is( $f2->(), 2, 'generator 2 once more' );
+# with ties
{
package countfetches;
our $fetchcount = 0;
@@ -78,8 +86,25 @@ is( $f2->(), 2, 'generator 2 once more' );
::is( $fetchcount, 1, "fetch only called once" );
}
+# state variables are shared among closures
+
+sub gen_cashier {
+ my $amount = shift;
+ state $cash_in_store = 0;
+ return {
+ add => sub { $cash_in_store += $amount },
+ del => sub { $cash_in_store -= $amount },
+ bal => sub { $cash_in_store },
+ };
+}
+
+gen_cashier(59)->{add}->();
+gen_cashier(17)->{del}->();
+is( gen_cashier()->{bal}->(), 42, '$42 in my drawer' );
+
+# stateless assignment to a state variable
+
sub stateless {
- # stateless assignment
(state $reinitme) = 42;
++$reinitme;
}