What is Perl object-oriented (OO)?

Perl has a class-based, Object-Oriented (OO) structure. We can implement (OOP)Object-Oriented Programming in Perl by creating packages, making classes, objects, and methods. The following core OOP features can also be implemented:

  • Encapsulation: Binding (or wrapping) code and data together into a single unit.

  • Abstraction: Hiding internal details and displaying only the functionality.

  • Inheritance: When one object acquires all the properties and behaviors of another class.

  • Polymorphism: Performing one task in different ways by different implementations of a method.

OOP Concept in programming languages

Perl’s object-oriented concepts

Perl’s object-oriented paradigm is slightly different from other OOP languages because:

  1. In Perl, a class is known as a package or a modulea reusable collection of related variables and subroutines that perform a set of programming tasks..

  2. An object is called referencea scalar variable that points or refers to another object such as a scalar, an array, a hash, etc. if it knows which class it belongs to.

  3. In Perl, a method is specified as a subroutinea block of code that can be reusable across programs..

Defining an OO class in Perl

Code

In the following example, the Car package is a class name, and the sub keyword is used to declare a subroutine named subroutine_car.

package Car;
sub subroutine_car {
my $class_name = shift;
my $self = ({
'CompanyName' => shift,
'CarName' => shift,
'CarModel' => shift
});
bless $self, $class_name;
return $self;
}
my $CarData = subroutine_car Car("Toyota",
"Corolla",
"Gli");
print "$CarData->{'CompanyName'}\n";
print "$CarData->{'CarName'}\n";
print "$CarData->{'CarModel'}";

Explanation

The shift keyword returns the first value in an array, removes it, and shifts the array list elements to the left by one.

The bless keyword before $self, $class_name is used to associate an object with a class.

Objects with $CarData are created using the my keyword followed by the module and package name.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved