programming-examples/perl/Class/A Perl class is a package containing a collection of variables and functions, called properties and methods.pl

38 lines
939 B
Perl
Raw Normal View History

2019-11-15 12:59:38 +01:00
There is no "class" keyword.
The properties are variables used to describe the object.
Methods are functions that create and manipulate the object.
Objects are created with the bless function.
#Creating a Class
package Pet
sub new{ # Constructor
my $class = shift;
my $pet = {
"Name" => undef,
"Owner" => undef,
"Type" => undef,
};
bless($pet, $class);
sub set_pet{
my $self = shift;
my ($name, $owner, $type)= @_;
$self->{'Name'} = $name;
$self->{'Owner'}= $owner;
$self->{'Type'}= $type;
}
sub get_pet{
my $self = shift;
while(($key,$value)=each($%self)){
print "$key: $value\n";
}
}
#Instantiating a Class
$cat = Pet->new();
# Create an object with a constructor method
$cat->set_pet("Sneaky", "Mr. Jones", "Siamese");
# Access the object with an instance
$cat->get_pet;