Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: How do YOU do OO in Perl?

by Nomad (Pilgrim)
on Oct 10, 2003 at 12:57 UTC ( #298236=note: print w/replies, xml ) Need Help??

in reply to How do YOU do OO in Perl?

At the moment, I generally just bless a hash and access its members (e.g. $self->{member}). As Abigail-II pointed out, though, this can make misspellings into tricky runtime errors. Also, the syntax seems kind of ugly to me.

Perhaps I'm being a bit dull here, but you could just use what is often called 'good manners', but is sometimes referred to as true OO. That is knock at the front door rather than sneak in through the cellar and use proper getter and setter methods to access your attributes and you can even do this without using things like Class::MethodMaker.

Of course, writing a load of getters and setters can get boring. Using AUTOLOAD without safeguards might cause all sorts of autovivification which is dangerous (I should know, I do it all the time).

Therefore the best way, IMHO, is the way that TheDamian suggests in Chapter 3 of his book, Object Oriented Perl, pp 91ff. This is to set up a hash to look after accessibility, like this:

{ my %_attr = { _attr1 => 'read', _attr2 => 'write', } sub _accessible { my ($self, $attr, $mode) = @_; $_attr{$attr} =~ /$mode/; } }

Then lower down you can have your AUTOLOAD:

sub AUTOLOAD { my ($self, $value) = @_; ## was it a get method? $AUTOLOAD =~ /.*::get(_\w+)/ and $self->_accessible($1, 'read') and re +turn $self->{$1}; ## was it a set method? $AUOTLOAD =~ /.*::get(_\w+)/ and $self->_accessible($1, 'write') and d +o { $self->{$1} = $value; return} die "No such method: $AUTOLOAD, $!"; }

Now, your program will die if you try to access an attribute that doesn't exist. Perhaps it would be better if it threw an exception if you try to set an attribute that is read-only, but in that version it doesn't.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://298236]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2017-06-28 17:41 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (641 votes). Check out past polls.