extern: index | reference
intern: preamble | sample | end
Perl supports object oriented programming very well, but as usual does it in its own way ;=)) There is no 'class' declaration, but the package name takes its place. The following example implements a 'Person' class, in the package, Person.pm, and then person01.pl shows how to initialize the 'class', add values to the members, and later access the values ...
This simple sample is based on this http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perltoot.pod page ... which contains a good explanation of all that is being done ... and there are many other 'pointers' in this document ... good reading ;=))
The 'Person' package, in a file called 'Person.pm' ...
code:
# Person - class implementation package Person; use strict; ############################################# ## the object constructor ## ############################################# sub new { my $class = shift; my $self = {}; $self->{NAME} = undef; $self->{AGE} = undef; $self->{PEERS} = []; bless ($self, $class); return $self; } ############################################## ## methods to access per-object data ## ## With args, they set the value. Without ## ## any, they only retrieve it/them. ## ############################################## sub name { my $self = shift; if (@_) { $self->{NAME} = shift } return $self->{NAME}; } sub age { my $self = shift; if (@_) { $self->{AGE} = shift } return $self->{AGE}; } sub peers { my $self = shift; if (@_) { @{ $self->{PEERS} } = @_ } return @{ $self->{PEERS} }; } 1; # so the require or use succeeds
And then a file, person01.pl, to use that class ...
# 11/10/2008 - testing using a class - object oriented stuff use strict; use warnings; use Person; # see Person.pm my ($him,@All_Recs); $him = Person->new(); # constructor $him->name("Jason"); # set 'name' $him->age(23); # 'age' $him->peers( "Norbert", "Rhys", "Phineas" ); # and 'peers' push @All_Recs, $him; # save object in array for later printf "%s is %d years old.\n", $him->name, $him->age; # access name and age print "His peers are: ", join(", ", $him->peers), "\n"; # show peers printf "Last record name is %s\n", $All_Recs[-1]->name;
output:
Jason is 23 years old. His peers are: Norbert, Rhys, Phineas Last record name is Jason
And that is it, for now ...
EOF - perl_class.htm