SPUG:Object property question
Sanford Morton
smorton at pobox.com
Wed Apr 30 20:53:02 CDT 2003
Here's one example, if I understand you correctly. Of course if this is a
database, you'll also need module routines to read to and write from the
database at the appropriate times, including the id number of the last member
created. I haven't tested any of this.
### code inside Member.pm ### code inside script
package Member; use Member;
use strict; my $m = Member->new('Jane', 'Doe');
print $m->id();
my $_lastid = 0; # class vble ==> prints id number
print $m->firstname('Mary');
sub new { # constructor ==> changes and prints first name
my $class = shift;
my $self = {};
$self->_init(@_);
return bless $self, $class;
}
sub _init { # initialization, private
my $self = shift;
$self->{'_firstname'} = $_[0];
$self->{'_lastname'} = $_[1];
$self->{'_id'} = ++$lastid;
}
sub firstname { # accessor, public
my $self = shift;
$self->{'_firstname'} = $_[0] if @_;
return $self->{'_firstname'};
}
sub id { # accessor, public
my $self = shift;
return $self->{'_id'};
}
I find it useful in module code to prefix with an underscore all internal
variables and functions (that aren't documented in the public interface and
aren't intended to be used by the user). If you're starved for another
introductory Perl object tutorial, you can scan the one at
http://www.speakeasy.org/~cgires/modules/
Or, for books, Damian Conway's is my favorite.
More information about the spug-list
mailing list