Object-Oriented Programming in Perl: Classes and Objects

April 18, 2024

Object-oriented programming (OOP) brings a new paradigm to Perl programming. This post will introduce the concepts of classes, objects, inheritance, and polymorphism in Perl, demonstrating the power of OOP in building scalable and maintainable code.

Classes and Objects

In Perl, classes are defined using the package keyword. A class typically resides in its own file with a .pm extension. The class file defines the attributes and methods of the class using the sub keyword for methods.

<pre><code>package Person;

sub new {
    my $class = shift;
    my $self = {
        name => shift,
        age => shift,
    };
    bless $self, $class;
    return $self;
}

sub get_name {
    my ($self) = @_;
    return $self->{name};
}

sub set_name {
    my ($self, $name) = @_;
    $self->{name} = $name;
}

1;
</code></pre>

To create an object of a class, we use the new constructor method. This method initializes the object’s attributes and blesses the reference to the class name. For example:

<pre><code>my $person = Person->new('Alice', 30);
print $person->get_name(); # Output: Alice
$person->set_name('Bob');
print $person->get_name(); # Output: Bob
</code></pre>

Inheritance

Perl supports single inheritance, where a class can inherit from another class using the ISA array. The child class can access the methods and attributes of the parent class. For example:

<pre><code>package Employee;
use parent 'Person';

sub new {
    my $class = shift;
    my $self = $class->SUPER::new(@_);
    $self-{salary} = shift;
    return $self;
}

sub get_salary {
    my ($self) = @_;
    return $self-{salary};
}

1;
</code></pre>

Polymorphism

Polymorphism in Perl allows methods to be overridden in the child class, providing different implementations. This enables flexibility and modularity in the codebase. For example:

<pre><code>sub get_name {
    my ($self) = @_;
    return 'Employee: ' . $self-{name};
}
</code></pre>

Object-oriented programming in Perl enhances code organization, reusability, and maintainability. Understanding classes, objects, inheritance, and polymorphism is essential for building robust and scalable Perl applications.