http://qs321.pair.com?node_id=245595

While thinking about programming languages in a half-sleep the other day I found myself wondering about closures and objects.

I have a somewhat favorite language (reflected by my nickname) which allows easy generation and manipulation of closures. Often I have heard things about objects and closures being related.

Since my Perl knowledge is somewhat limited (I own the Camel book, but never read it in full), I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.

First I will pre-emptively apologize for the somewhat confusing "object" term I use, and admit I don't know much about Perl's real object system.

Ok, so I ended up with the following thing, which is basically a simple object system (message passing):

# 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"; } }
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.

Here is some example code using this thing:

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

So what's the value of all of this? Well, I don't think this code could be of some use in practice, since it is more like a toy example and the syntax just doesn't cut it. But at the very least I had some fun writing it, and hopefully it can be seen as a demonstration of what closures allows you to do.

Comments, thoughts and/or insults would be appreciated! :-)

Schemer