(Your Perl distribution may not include Class::Accessor, in which case you'd need to install it from CPAN.)
Here's an example of how you might use Class::Accessor:
package MyPerson;
use base qw/ Class::Accessor /;
MyPerson->mk_accessors(
qw/
fname
mname
lname
birthdate
address
/
);
1;
Then in your Perl program:
use MyPerson;
my $person = MyPerson->new(
{
fname => 'Homer',
mname => 'Jay',
lname => 'Simpson',
birthdate => '1 January 1970',
}
);
my $birthdate = $person->birthdate(); # $birthdate is now '1 January 1970'
$person->address('742 Evergreen Terrace, Springfield'); # sets the address attribute
Note that you didn't have to explicitly write a constructor--your code just gives new() a hashref of the attributes you want to set.
You can now even use MyPerson as a base class. Another package can inherit from MyPerson and add its own attributes:
package MyCustomer;
use base qw/ MyPerson /;
MyCustomer->mk_accessors(
qw/
billing_address
shipping_address
/
);
1;
The documentation for Class::Accessor is worth reading--it offers ways to declare read-only and write-only attributes (the former would only have accessors, and the latter would only have mutators).
No comments:
Post a Comment