Accessors
Accessor methods give controlled access to an object's data instead of poking at the hash directly.
In this page:
Accessors
A getter returns a field and a setter changes it, and often one method does both depending on whether an argument was supplied. Using accessors hides the internal structure, so you can change the representation later without breaking callers. You can generate several accessors from a list of names by assigning closures into the symbol table with no strict refs.
Note:
Test the number of arguments with @_ > 1 rather than defined, so callers can set a field to undef.
Example: Accessors
use strict;
use warnings;
package Person;
sub new {
my ($class, %args) = @_;
return bless { name => $args{name}, age => $args{age} }, $class;
}
sub name {
my $self = shift;
$self->{name} = shift if @_;
return $self->{name};
}
for my $field (qw(age email)) {
no strict 'refs';
*{"Person::$field"} = sub {
my $self = shift;
$self->{$field} = shift if @_;
return $self->{$field};
};
}
package main;
my $p = Person->new(name => "Ada", age => 36);
print $p->name, " is ", $p->age, "\n";
$p->name("Ada Lovelace");
$p->age(37);
$p->email('[email protected]');
print $p->name, " is ", $p->age, ", email: ", $p->email, "\n";
$p->age(0);
print "age set to 0: ", $p->age, "\n";
# Output:
# Ada is 36
# Ada Lovelace is 37, email: [email protected]
# age set to 0: 0
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Reaching into $obj->{field} from outside the class
- Testing a setter argument for truth and rejecting 0 or an empty string
- Forgetting to return the value in the getter
Chapter Summary
- Accessors get and set fields
- They hide internal structure
- Check @_ to see if a value was supplied
- Closures can generate accessors
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: