3
accessors::ro - create 'classic' read-only accessor methods in caller's package.
8
use accessors::ro qw( foo bar baz );
10
my $obj = bless { foo => 'read only? ' }, 'Foo';
12
# values are read-only, so set is disabled:
13
print "oh my!\n" if $obj->foo( "set?" ) eq 'read only? ';
15
# if you really need to change the vars,
16
# you must use direct-variable-access:
17
$obj->{bar} = 'i need a drink ';
20
# always returns the current value:
21
print $obj->foo, $obj->bar, $obj->baz, "!\n";
25
package accessors::ro;
28
use warnings::register;
29
use base qw( accessors );
31
our $VERSION = '1.01';
32
our $REVISION = (split(/ /, ' $Revision: 1.4 $ '))[2];
34
use constant style => 'ro';
37
my ($class, $accessor, $property) = @_;
38
# get is slightly faster if we eval instead of using a closure + anon
39
# sub, but the difference is marginal (~5%), and this uses less memory...
41
*{$accessor} = sub { return $_[0]->{$property} };
50
The B<accessors::ro> pragma lets you create simple I<classic> read-only
51
accessors at compile-time.
53
The generated methods look like this:
60
They I<always> return the current value, just like L<accessors::ro>.
64
There is B<little-to-no performace hit> when using generated accessors; in
65
fact there is B<usually a performance gain>.
71
typically I<5-15% faster> than hard-coded accessors (like the above example).
75
typically I<0-15% slower> than I<optimized> accessors (less readable).
79
typically a I<small> performance hit at startup (accessors are created at
84
uses the same anonymous sub to reduce memory consumption (sometimes by 80%).
88
See the benchmark tests included with this distribution for more details.
92
Classes using blessed scalarrefs, arrayrefs, etc. are not supported for sake
93
of simplicity. Only hashrefs are supported.
97
Steve Purkis <spurkis@cpan.org>
103
L<accessors::classic>,
104
L<accessors::chained>,