# perl program illustrating closures and a kind of objects sub mktoggle { my $v = $_[0]; if ($v>1 || $v<0) {die "what planet are you from?"} sub { $v = ($v+1) % 2; $v } } $t1 = mktoggle(0); $t2 = mktoggle(1); print $t1->(), "\n"; # changes state print $t2->(), "\n"; # Clearly, t1 and t2 are functions that carry STATE information. They # share the SAME SOURCE CODE, but they are clearly different entities! # Their behavior is more like those of methods as opposed to functions. # now expand - there's other information we may want concerning the local # state of these functions - we may want to see the current value of v # without changing it, or we may wish to reset it to zero. In other words, # we want three operations to be associated with the local state that was # created: # toggle: toggles value and returns new value # getval: returns value without toggling # reset: reset value to zero sub mktginstance { my $v = $_[0]; if ($v>1 || $v<0) {die "what planet are you from?"} my $toggle = sub { $v = ($v+1) % 2; $v }; my $getval = sub { $v }; my $reset = sub { $v = 0; }; # Now for the INTERFACE function: sub { my $request = $_[0]; if ($request eq "getval") {return $getval->();} if ($request eq "toggle") {return $toggle->();} if ($request eq "reset") {return $reset->(); } else {"request denied"} } } # mktginstance $t1 = mktginstance(0); $t2 = mktginstance(1); print "------------\n"; print $t1->(getval), "\n"; $t1->(toggle); print $t1->(getval), "\n"; $t1->(reset); print $t1->(getval), "\n";