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 paradigm is slightly different from other OOP languages because:
In Perl, a class is known as a package or a
An object is called
In Perl, a method is specified as a
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'}";
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