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!

London, the Perl city

Published by marco on 2009-01-31

If you are a Perl developer (or just passionate about this language), then London is definitely the city to live in. The Perl community in the city is quite active, as you can see from the number of free events available every couple of months. Last November I attended the London Perl Workshop, where a former colleague from Yahoo was giving some talks about Moose. The next month, February 19th, I will attend the London.pm technical meeting where, guess what, Moose will be the star again. The event will take place at the BBC’s offices near White City from 7pm to 9pm. If you are in town and you want to join, make sure to register as places are limited.

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