Dynamically generated attribute accessors in Perl In my spare time I'm working at a perl library, which is the lightweight implementation of a package I did some time ago. In the previous iteration I used Moose as object-oriented framework, as suggested by many people on the Internet.

Later in time I realized how Moose was a total overkill for my use case (I'm not a big fan of the 8-hours dependencies setup time), and that's the reason why I went for a refactoring.

Suddenly I found myself to face a situation where I want something similar to what I used to have with Moose, but in a far simper way: I would like one of my modules to have simple setter/getter properties without manually defining all of them.

I came out with the following simple implementation, which seems to be quite effective:

#!/usr/bin/perl -w

use strict;
use warnings;

package Foo;

BEGIN {
    no strict 'refs';
    foreach my $mname (qw/bar baz/) {
        *$mname = sub {
            my $self = shift;
            if (@_) {
                $self-&gt;{$mname} = shift
            } else {
                $self-&gt;{$mname}
            }
        }
    }
}

sub new { bless {}, shift }


What do you think of it? Do you see any evident drawback? This is the code I used for testing it, and it seems to work just fine:

package main;

use feature 'say';

my $x = Foo-&gt;new();
for (1 .. 10) {
    $x-&gt;bar($_);
    say 'bar: ', $x-&gt;bar;
    say 'baz: ', $x-&gt;baz || '&lt;none&gt;';
    $x-&gt;baz($_);
}
$x-&gt;goat_cheese(3) # broken
If Moose is an overkill, you can try Moo instead. There are some even simpler distributions like Class::Tiny or Object::Tiny. They are probably better tested than your own solution as their user base is larger. They might also be faster (more optimized) and play well with inheritance and roles.