September 11, 2004

Reformed Perl - Third millenium syntax for Perl 5 OOP

One day I looked at all the hacks and detours necessary to have Perl perform the most basic OOP, and decided that I'm not going to take it anymore.

Enter Reformed Perl, a pragma that pulls Perl 5 OOP syntax into the year 2004. Here is a rundown of the things it does:

Shorthand inheritance

Rather than using the cumbersome use base 'Parent' you may write:

    package Child < Parent;

Shorthand parameters

It is no longer necessary to fish method parameters out of @_:

    sub method($foo, $bar)
        print "First param: $foo";
        print "Second param: $bar";

Implicit self, class and base

References to the instance, the class (package) and the base class are implicitely provided as self, class and base:

    sub method

Pretty field accessors

You may omit the curly brackets in self->{foo} if you declare your field names using fields:

    fields foo, bar;
    sub method {
        self->foo = "some value";
        print self->foo;

You may intercept read and write access to instance fields by overwriting getter and setter methods:

    fields foo;
    sub get_foo
        print "Getting foo!";
        return self->{foo};
    sub set_foo($value)
        print "Setting foo!";
        self->{foo} = $value;

Clean constructors

All reformed packages inherit a basic constructor new from the Class package. When you need custom contructors, don't overwrite new - overwrite initialize:

    use reform;
    package Amy;
    fields foo,
    sub initialize($foo)
        self->foo = $foo;

You may call the constructor of a base class by calling base->initialize().

Reformed packages are fully compatible to old school Perl code. Join the Reform today!