NAME
accessors - create accessor methods in caller's package.
SYNOPSIS
package Foo;
use accessors qw( foo bar baz );
my $obj = bless {}, 'Foo';
# generates chaining accessors:
$obj->foo( 'hello ' )
->bar( 'world' )
->baz( "!\n" );
print $obj->foo, $obj->bar, $obj->baz;
DESCRIPTION
The accessors pragma lets you create simple accessors at compile-time.
This saves you from writing them by hand, which tends to result in cut-n-paste errors and a mess of duplicated code. It can also help you reduce the ammount of unwanted direct-variable access that may creep into your codebase when you're feeling lazy. accessors was designed with laziness in mind.
Method-chaining accessors are generated by default. This may be changed in future versions! If you want backwards compatability use accessors::chained and wait until the dust settles.
See accessors::classic for accessors that always return the current value if you don't like method chaining.
GENERATED METHODS
accessors will generate methods that return the current object on set:
sub foo {
my $self = shift;
if (@_) { $self->{-foo} = shift; return $self; }
else { return $self->{-foo}; }
}
This way they can be chained together.
PERFORMANCE
There is little-to-no performace hit when using generated accessors; in fact there is usually a performance gain.
typically 10-30% faster than hard-coded accessors (like the above example).
typically 1-15% slower than optimized accessors (less readable).
typically a small performance hit at startup (accessors are created at compile-time).
uses the same anonymous sub to reduce memory consumption (sometimes by 80%).
See the benchmark tests included with this distribution for more details.
MOTIVATION
The main difference between the accessors pragma and other accessor generators is simplicity.
interface
use accessors qw( ... ) is as easy as it gets.
a pragma
it fits in nicely with the base pragma:
use base qw( Some::Class ); use accessors qw( foo bar baz );
and accessors get created at compile-time.
no bells and whistles
The module is extensible instead.
SUB-CLASSING
If you prefer a different style of accessor or you need to do something more complicated, there's nothing to stop you from sub-classing. Look through accessors::classic to start.
CAVEATS
Classes using blessed scalars or arrays are not supported.
THANKS
Thanks to Michael G. Schwern for indirectly inspiring this module, and for his feedback & suggestions.
Also to Paul Makepeace and David Wright for showing me faster accessors, and to James Duncan and people on London.pm for their feedback.
AUTHOR
Steve Purkis <spurkis@epn.nu>
SEE ALSO
accessors::classic, accessors::chained
Similar and related modules:
base, fields, Class::Accessor, Class::Struct, Class::Methodmaker, Class::Generate, Class::Class, Class::Tangram