More Advancements in Perl Programming

Simon Cozens is an author more than 90 CPAN modules and second edition of Advanced Perl Programming published an article on Perl.com where he gave some significant additions since first edition.
The most interesting for me in this article was a mention about module Class::Accessor. I use Class::DBI for a long time. It lightens the routine work when you need to develop some classes which represent database tables orr saying in OO terms to produce persistent objects. As I understand Class::Accessor does the same but for non persistent object too.
Here is an example. Usually, to develop a simple class we should implement method new() and some accessors:

package MyClass;

sub new { bless { %{@_} }, shift; }

sub name {
    my $self = shift;
    $self->{name} = shift if @_;
    $self->{name}
}

sub address {
    my $self = shift;
    $self->{address} = shift if @_;
    $self->{address}
}

But using of Class::Accessor saves a lot of your time:

package MyClass;
use base qw(Class::Accessor);

__PACKAGE__->mk_accessors(qw( name address ));

Cool, isn’t it? Additionaly there is a possibility to specify read-only accessors or separate them on read and wtite. Defenatelly, I’ll use this module to develop new modules and improve existing.

Leave a Reply

Your email address will not be published. Required fields are marked *