Basically, this creates an object that only has one "method" initially, which allows for the addition of other methods or slots ("member values"). Methods added are internally stored in a hash which is local to the object's closure.# an object is simply a closure with a hash of closures sub make_object { my %msg; $msg{"add-msg"} = sub { my $m = shift(); $msg{$m} = shift(); }; return sub { my $m = shift(); return $msg{$m} ? $msg{$m}->(@_) : print "unknown message\n"; } }
# build an object my $object = make_object(); # add functions to our object &$object("add-msg", "status", sub {print "up and running\n"}); &$object("add-msg", "square", sub {return shift()**2}); # test the functions &$object("status"); # ==> displays "up and running" print &$object("square", 25.80697580112788) . "\n"; # ==> "666" # here is something fun... &$object("add-msg", "build-object", \&make_object); # ...objects can generate objects my $other_object = &$object("build-object"); &$other_object("status"); # ==> error, this is a distinct object &$other_object("add-msg", "status", sub {print "new object up\n"}); &$other_object("status"); # ==> display "new object up" # an object could manipulate itself &$object("add-msg", "get-self", sub {return $object}); &$object("get-self")->("add-msg", "test", sub {print "test ok!\n"}); &$object("test"); # ==> display "test ok!"
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Fun with Closures
by Anonymous Monk on Mar 25, 2003 at 02:24 UTC | |
by Corion (Patriarch) on Mar 25, 2003 at 08:08 UTC | |
Re: Fun with Closures
by rjray (Chaplain) on Mar 25, 2003 at 02:27 UTC | |
Re: Fun with Closures
by jdporter (Paladin) on Mar 25, 2003 at 02:28 UTC | |
by Abigail-II (Bishop) on Mar 25, 2003 at 08:11 UTC | |
by jdporter (Paladin) on Mar 25, 2003 at 17:59 UTC | |
Re: Fun with Closures
by dada (Chaplain) on Mar 26, 2003 at 08:11 UTC | |
Re: Fun with Closures
by hardburn (Abbot) on Mar 25, 2003 at 14:57 UTC |