The difference between the class and the object (instance) may be reminiscent of the relationship between Plato's Ideal and Real.
- starting simply: blessing a reference into a class
$dogname = 'Fido';
$dogObj = \$dogname;
bless($dogObj, Pets);
- Constructors
The construction of a particular object is usually handled in an automated manner.
package Pen;
sub new {
#constructor
#USAGE: Pen->new;
# the class is the first arg passed to a class function
my $class = shift; #@_ is assumed.
# this will be cleaner when working with anonymous hashes and arrays
my $penType = 'not specified';
my $penRef = \$penType;
# creates the (object) instance reference and return it.
bless $penRef, $class;
}#end, constructor
#thank you, drive through
1;
- passing an argument to the constructor
package Pen;
sub new {
#constructor
#USAGE: Pen->new("type of pen");
# the class is the first arg passed to a class function
my $class = shift; #@_ is assumed. remember that shift is destructive
my $penType = shift; #now the passed arg
# this will be cleaner when working with anonymous hashes and arrays
my $penRef = \$penType;
# created the object reference and return it.
bless $penRef, $class;
}#end, constructor
#thank you, drive through
1;
- Holding real object data: hashes instead of scalars
package Pen;
sub newValues {
#constructor
#USAGE $ref = Pen->newValues('pen type', 'pen color', 'ink color');
# just doing this to keep your head straight
my $class = $_[0];
my $penType = $_[1];
my $penColor = $_[2];
my $inkColor = $_[3];
# anonymous hash!
my $penRef = { penType => $penType,
penColor => $penColor,
inkColor => $inkColor,
};
# created the instance reference and return it.
bless $penRef, $class;
}#end, constructor
#thank you, drive through
1;
Remember, your login is based on your machine's hostname, not on any other number.
~/[initials] refers to the subdirectory under your homedir, named after your initials. Everything except for .dotfiles will be stored in your ~/[initials] directory.