# 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!"