Adding attribute accessors to a Perl class – rubifying perl

Published by marco on 2009-02-03

This small hack adds attribute accessors to a Perl class. The idea is to add to a Perl package behavior similar to a Ruby class, when you can specify attribute accessors (getters and setters) like this:

attr_accessor :attr_name

Here is the code we have written. Basically all you need to do is add the sub attr_accessor to your Perl class, and then call this method with the attribute you want the getter and setter for.

package MyPackage;
 
sub new {
  my $class = shift;
  bless {}, $class;
}
 
sub attr_accessor {
  $attr = shift;
  eval <<ATT;
  sub $attr {
    my \$self = shift;
    my \$value = shift;
    if( \$value ) {
      my \$old_value = \$self->{ $attr };
      \$self->{ $attr } = \$value;
      return \$old_value;
      } else {
        return \$self->{ $attr };
      }
    }
ATT
}
 
attr_accessor 'name';

In the code above we have added accessors methods for the attribute ‘name’. We can then set and get the ‘name’ attribute as in the following code:

my $t = new MyPackage;
$t->name('marco'); # setter method
print $t->name # this will get and print 'marco'

Enjoy!

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2010 xterm.it | powered by WordPress based on Barecity