Notifications
Clear all
Topic starter 01/08/2025 11:37 pm
While Perl isn’t traditionally object-oriented like Java or Python, it can support object-oriented programming (OOP), and classes in Perl are just packages with a bit of extra structure.
Here’s a friendly primer:
🏗️ What Is a Class in Perl?
- A class is essentially a Perl package that encapsulates data and methods
- You define it using the
package
keyword - Objects are usually created using
bless
, which associates a reference with a class
package Animal;
sub new {
my $class = shift;
my $self = {
name => shift,
sound => shift,
};
bless $self, $class;
return $self;
}
🐾 Creating and Using an Object
my $dog = Animal->new("Fido", "Bark");
print $dog->{name}; # prints Fido
print $dog->{sound}; # prints Bark
🧠 Adding Methods to Your Class
sub speak {
my $self = shift;
print $self->{name} . " says " . $self->{sound} . "\n";
}
Call it like this:
$dog->speak(); # prints "Fido says Bark"
🔗 Inheritance in Perl
Perl supports inheritance by using the @ISA
array:
package Dog;
our @ISA = qw(Animal);
This lets Dog
inherit methods from Animal
.