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
{
self->instance_method();
class->static_method();
base->super_class_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,
bar;
sub initialize($foo)
{
self->foo = $foo;
}
You may call the constructor of a base class by calling base->initialize().
Comments
Is this in the CPAN yet?
Posted by Randal L. Schwartz (#)
This is the first time I'm trying to submit anything to CPAN, and the PAUSE FAQ on module submissions is giving me some headaches.
More specifically I don't know if I'm supposed to add the HTMLified POD from my modules to my distribution archive, of it is going to be generated automatically from the package files. Also I'm not certain about how to understand the advice about $VERSION, and whether I need a README and MakeFile.PL.
Posted by
Henning
(#)
You don't need an HTMLified POD or a README.
README is nice but not absolutly necessary. Just use this entry for the README.
Makefile.PL -- please! It would be nice to install this package in the standard way.
See Module::Starter for more help: http://search.cpan.org/~rjbs/Module-Starter/lib/Module/Starter.pm
Posted by Mark A. Hershberger (#)
If you don't already have a CPAN id, you'll want to register for one immediately at https://pause.perl.org/pause/query?ACTION=request_id
Posted by Richard Soderberg (#)
Thank you Richard, I received my CPAN id some time ago. Everyone was very helpful to get my module published.
Posted by
Henning
(#)