Forum

Learn Perl Classes
 
Notifications
Clear all

Learn Perl Classes

1 Posts
1 Users
0 Reactions
9 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

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.


 


   
Quote
Share: