"Perl for Perl Newbies" - Part 5 - Good Programming PracticesClass AccessorsAccessor modules on the CPAN

4.3. Accessor modules on the CPAN

As you may have noticed from our example, writing accessors by hand involves a lot of duplicate code, and can get tedious. One way to overcome it is by using namespace games (e.g: *Person::${field} = sub { .... }), but there are many modules on CPAN that do it all for you. Here's an overview of some of the most prominent ones:


Class-Accessorwas one of the earliest accessor providing modules and is still pretty popular. It is pure Perl, has no dependencies, and works pretty well. It has many enhancements on CPANthat may work better for you.


Class-XSAccessor is an accessor generator partially written using C and Perl/XS which is the Perl external subroutine mechanism. As such, it provides an unparalleled speed among the other accessor generators, and is even faster than writing your own accessor methods by hand, like we did in the example.


While Moose provides accessors, they are only the tip of its iceberg. Moose is in fact a “post-modern” object system for Perl 5 that provides a type system, delegators, meta-classes, wrapping routines, and many other advanced features. As I once said:

Every sufficiently complex Class::Accessor program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Moose.

If you're looking to take your object oriented programming in Perl 5 to new levels - look no further than that. One should be warned that as of this writing (August, 2009), Moose may have a relatively long startup time, although the situation has been improved and is expected to improve further.

Written by Shlomi Fish