13 June 2006

Perl's Class::Accessor

If you find yourself writing a Perl module for a class with a large number of attributes and a correspondingly large number of accessors and mutators ('getters' and 'setters'), you might want to try Class::Accessor. With Class::Accessor as a base class, your module can just declare its attributes, and Class::Accessor will generate all the accessors and mutators (and the constructor) automatically.

(Your Perl distribution may not include Class::Accessor, in which case you'd need to install it from CPAN.)

Here's an example of how you might use Class::Accessor:

package MyPerson;
use base qw/ Class::Accessor /;


Then in your Perl program:

use MyPerson;

my $person = MyPerson->new(
fname => 'Homer',
mname => 'Jay',
lname => 'Simpson',
birthdate => '1 January 1970',

my $birthdate = $person->birthdate(); # $birthdate is now '1 January 1970'
$person->address('742 Evergreen Terrace, Springfield'); # sets the address attribute

Note that you didn't have to explicitly write a constructor--your code just gives new() a hashref of the attributes you want to set.

You can now even use MyPerson as a base class. Another package can inherit from MyPerson and add its own attributes:

package MyCustomer;
use base qw/ MyPerson /;


The documentation for Class::Accessor is worth reading--it offers ways to declare read-only and write-only attributes (the former would only have accessors, and the latter would only have mutators).

04 June 2006

Lightswitches are evil

I really hate standard lightswitches.

Evidently, I have this irrational, deep-seated aversion to touching lightswitches. Dunno why. But when I want to turn one on or off, I just naturally swing at it with the intention of barely and briefly touching it with my fingertip.

Trouble is, I usually miss. Which angers me. So I swing at it again, only harder, to punish it for evading me. So, of course, I miss again, which angers me more. This continues until I typically end up hitting the lightswitch with a shoe or something.

If I had any sense, or if I were a normal person, I'd just calmly and sanely sweep my whole hand down (or up) over the lightswitch. But that apparently entails more physical contact than my neurosis can withstand.

Maybe I need one of these: http://www.gogglemarks.net/index.php?action=display&tag=fightswitch