Using Perl and Moose
, object data can be accessed in 2 ways.
$self->{attribute}
or $self->attribute()
Here is a simple example demonstrating both:
# Person.pm
package Person;
use strict;
use warnings;
use Moose;
has 'name' => (is => 'rw', isa => 'Str');
has 'age' => (is => 'ro', isa => 'Int');
sub HAPPY_BIRTHDAY {
my $self = shift;
$self->{age}++; # Age is accessed through method 1
}
sub HAPPY_BIRTHDAY2 {
my $self = shift;
my $age = $self->age();
$self->age($age + 1); # Age is accessed through method 2 (this will fail)
}
1;
# test.pl
#!/usr/bin/perl
use strict;
use warnings;
use Person;
my $person = Person->new(
name => 'Joe',
age => 23,
);
print $person->age()."\n";
$person->HAPPY_BIRTHDAY();
print $person->age()."\n";
$person->HAPPY_BIRTHDAY2();
print $person->age()."\n";
I know that when you are outside of the Person.pm
file it is better to use the $person->age()
version since it prevents you from making dumb mistakes and will stop you from overwriting a read only value, but my question is...
Inside of
Person.pm
is it best to use$self->{age}
or$self->age()
? Is it considered bad practice to overwrite a read-only attribute within the module itself?Should this attribute be changed to a read/write attribute if its value is ever expected to change, or is it considered acceptable to override the read-only aspect of the attribute by using
$self->{age}
within theHAPPY_BIRTHDAY
function?
$person->{age} = $person->is_baby() ? 1 : 52;
. How do you do something like that following the correctMoose
format? – Quiff