Perl OOP: Object-Oriented Programming Guide
In Perl, object-oriented programming involves defining a class first, then creating objects and calling methods of the class. Here is a simple example:
# 定义一个类
package Person;
sub new {
my $class = shift;
my $self = {
name => shift,
age => shift,
};
bless $self, $class;
return $self;
}
sub get_name {
my $self = shift;
return $self->{name};
}
sub get_age {
my $self = shift;
return $self->{age};
}
1;
# 创建对象并调用方法
my $person = Person->new("Alice", 25);
print "Name: " . $person->get_name() . "\n";
print "Age: " . $person->get_age() . "\n";
In the example above, a class named Person is first defined, which includes a constructor method called new and two instance methods called get_name and get_age. An instance of Person is then created by calling the new method of the Person class, and the get_name and get_age methods are called to access the object’s property values.
It is important to note that in Perl, using the bless function binds a hash reference to a class name to create an object. Methods of the object can then be called using the arrow operator ->.