Chad Perrin: SOB

1 August 2006

Example Class and Instantiation of Perl Closure-Object

Filed under: Cognition,Geek — apotheon @ 02:58

Many many moons ago, SOB (that’s where you are now) hosted a discussion of the idea of an object model based on lexical closures for the Perl programming language. Blame the sugar, or the fact I’ve been sleeping poorly, or whatever you like, but I’m going to make a half-baked attempt at actually demonstrating the creation of a class, with methods, plus instantiation of the closure-object and passing messages to it.

sub counter {
  my $int = shift;

  return sub {
    my $msg = shift;
    if ($msg eq 'inc') {
      print ++$int . "\\n";
    } elsif ($msg eq 'dec') {
      print --$int . "\\n";
    } else {
      $int = 0;

my $count = counter(0);


That should give output that looks something like this:

1 2 1 -1

It’s a new way of thinking about objects in Perl, sorta. At least, it looks new to me, since it’s not the “official” Perl object model, and nobody else seems to be doing it, but it achieves the necessary characteristics of a working object model.

This particular example covers three of the four OOP menu-items I listed in the above-referenced SOB post as being covered by a closure-object model in Perl: AYCDISAM, encapsulation, and protection. It doesn’t touch inheritance — something I’ll probably address at some later date.

All original content Copyright Chad Perrin: Distributed under the terms of the Open Works License