in reply to Re: Re: My first package - need help getting started
in thread My first package - need help getting started
Ok, let's assume that the opaque object is implemented internally as a hashref, and that the fullname has a simple format of "surname, initials". Here's a simplistic approach:
package Person; sub fullname { my $self = shift; if (@_) { $self->{fullname} = shift; } return $self->{fullname}; } sub initials { my $self = shift; if (@_) { $self->fullname(join ', ', $self->surname, shift); } (split $self->fullname, ', ', 2)[1]; } sub surname { my $self = shift; if (@_) { $self->fullname(join ', ', shift, $self->initials); } (split $self->fullname, ', ', 2)[0]; }
In practice, I'd write it a bit differently: I'd probably have many methods very similar to fullname(), and might well generate them rather than write each one out explicitly. Also, I'd probably cache the derived information like surname and initials, to avoid recalculating them each time, in which case I'd need to be careful to decache that information when the source (fullname in this case) changed.
I'm surprised that you don't want the module to parse the data for you, since that seems to be a chunk of code that you'd otherwise need to repeat everywhere you deal with these records. But likely I've misunderstood what you're trying to do.
I guess the most important thing, which I should have said before, is that documentation is the key, particular in perl: the docs for your class will say how you're allowed to use the object, and what you're allowed to assume about it. And in general, anything that the docs don't say you are not allowed to do or assume when using the class or its objects in other code.
Hugo
|
|---|