I would highly recommend reading
Damian Conway's Book
Object-Oriented Perl for
a project like this. Just flipping through my copy, I came
accross this example on page 92, where he address the issue of data hiding by using the AUTOLOAD function.
package CD::Music;
use strict;
use vars '$AUTOLOAD'; # Keep 'use strict' happy
{
my %_attrs =
( _name => undef,
_artist => undef,
_publisher => undef,
_ISBN => undef,
_tracks => undef,
_rating => undef,
_room => undef,
_shelf => undef,
);
sub _accessible { exists $_attrs{$_[1]} }
}
sub AUTOLOAD
{
my ($self) = @_;
$AUTOLOAD =~ /.*::get(_\w+)/
or croak "No such method: $AUTOLOAD";
$self->_accessible($1)
or croak "No such attribute: $1";
$self->{_read_count}++;
return $self->($1);
}
This will dynamically create methods such as
getname to access the underlying data, rather
than letting someone poke at it willy-nilly. This keeps your access methods and your data in sync. It also allows for easier error checking, since all your methods
are being dynamically defined in one place.
-Blake
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.