Perl supports object-oriented programming (OOP) through its flexible and powerful class and object system. This guide will introduce you to the basics of working with classes and objects in Perl.
In Perl, a class is typically defined using a package. Here's a simple example:
package Person;
sub new {
my $class = shift;
my $self = {
name => shift,
age => shift,
};
bless $self, $class;
return $self;
}
sub greet {
my $self = shift;
print "Hello, my name is $self->{name} and I'm $self->{age} years old.\n";
}
1;
This code defines a Person
class with a constructor (new
) and a method (greet
).
To create and use an object, you can do the following:
use Person;
my $person = Person->new("Alice", 30);
$person->greet();
This will output: "Hello, my name is Alice and I'm 30 years old."
bless
function is used to associate a reference with a package, effectively creating an object.@ISA
array. For more details, see Perl Inheritance.strict
and warnings
pragmas in your class definitions.Moose
or Moo
modules for more advanced OOP features.As you become more comfortable with Perl's OOP system, you may want to explore:
Understanding classes and objects is crucial for leveraging Perl's OOP capabilities. With practice, you'll be able to create complex, maintainable object-oriented Perl programs.