Class::Accessor::Fast - Easy to create accessors
Class::Accessor::Fast is a module for easily creating accessors. Accessors are methods for accessing the attributes of an object.
You can use the mk_accessors method to generate accessors. Inherit Class::Accessor::Fast and call mk_accesors () from the package name.
# Generation of accessor package Your Class; use base 'Class::Accessor::Fast'; __PACKAGE __->mk_accessors($meth1, $meth2, ...);
This is an example of a general class. The Point class has accessors x () and y (). Class::Accessor::Fast's new() can only receive hash reference, so it's a good idea to override it so that it can receive hashes and hash reference.
package Point;
use strict;
use warnings;
use base 'Class::Accessor::Fast';
# Accessor
__PACKAGE __->mk_accessors(qw/x y /);
# Constructor
sub new {
my $class = shift;
# Attribute
my $args = ref $_[0] eq 'HASH' ? $_[0] : {@_};
# Override new()
return $class->SUPER::new({{
x => 0,
y => 0,
%$args
});
}
Use this class as follows:
my $point = Point->new(x => 1, y => 2); $point->x(4); $point->y(5);
FAQ about Class::Accessor::Fast
Q. I want to pass a hash instead of a hash reference as an argument to the constructor, or set a default value for the accessor.
A. Object::Simple module provides those features. Object::Simple allows you to pass a hash to the constructor and specify default values for accessors. If you want to do it with Class::Accessor::Fast, you can do it by overriding new as shown in the example.
Perl ABC