| 1 | =head1 NAME | ||
| 2 | |||
| 3 | accessors::ro - create 'classic' read-only accessor methods in caller's package. | ||
| 4 | |||
| 5 | =head1 SYNOPSIS | ||
| 6 | |||
| 7 | package Foo; | ||
| 8 | use accessors::ro qw( foo bar baz ); | ||
| 9 | |||
| 10 | my $obj = bless { foo => 'read only? ' }, 'Foo'; | ||
| 11 | |||
| 12 | # values are read-only, so set is disabled: | ||
| 13 | print "oh my!\n" if $obj->foo( "set?" ) eq 'read only? '; | ||
| 14 | |||
| 15 | # if you really need to change the vars, | ||
| 16 | # you must use direct-variable-access: | ||
| 17 | $obj->{bar} = 'i need a drink '; | ||
| 18 | $obj->{baz} = 'now'; | ||
| 19 | |||
| 20 | # always returns the current value: | ||
| 21 | print $obj->foo, $obj->bar, $obj->baz, "!\n"; | ||
| 22 | |||
| 23 | =cut | ||
| 24 | |||
| 25 | package accessors::ro; | ||
| 26 | |||
| 27 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 28 | 1 | ▶ | use warnings::register; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 29 | 1 | ▶ | use base qw( accessors ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 30 | |||
| 31 | 1 | our $VERSION = '1.01'; | |
| 32 | 1 | our $REVISION = (split(/ /, ' $Revision: 1.4 $ '))[2]; | |
| 33 | |||
| 34 | 1 | ▶ | use constant style => 'ro'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 35 | |||
| 36 | 3 | ▶ | sub create_accessor { |
|
Subroutine
create_accessor: called CC=1 SCAR=0.0
Pod
undocumented
| |||
| 37 | 3 | 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... | ||
| 40 | 1 | ▶ | no strict 'refs'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 41 | 3 | ▶ | *{$accessor} = sub { return $_[0]->{$property} }; |
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||
| 42 | } | ||
| 43 | |||
| 44 | 1 | 1; | |
| 45 | |||
| 46 | __END__ | ||