What is Perl object-oriented (OO)?
Perl has a class-based, Object-Oriented (OO) structure. We can implement
-
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.
Perl’s object-oriented concepts
Perl’s object-oriented paradigm is slightly different from other OOP languages because:
-
In Perl, a class is known as a package or a
.module a reusable collection of related variables and subroutines that perform a set of programming tasks. -
An object is called
if it knows which class it belongs to.reference a scalar variable that points or refers to another object such as a scalar, an array, a hash, etc. -
In Perl, a method is specified as a
.subroutine a 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