Perl has a class-based Object-Oriented (OO) structure that gives us the flexibility to use various new features, such as packages and modules, in Perl.
A package is a collection or code group in Perl. Meanwhile, a module in Perl is a package defined in a file with the name “package” and the the extension .pm.
We can only define the package once in a program; whereas, more than one different module can have the same name in a single code file.
A package name must always be at the start of a Perl program.
Consider the following code syntax with two Car
and Motorbike
), and a Vehicle
package at the top of the code file.
# Package definitionpackage Vehicle;sub Car{print "This is a car subroutine!\n";}sub Motorbike{print "This is a motorbike subroutine!\n";}
The following example shows how to import a package into our code file with the use
keyword.
# Using package Vehicleuse Vehicle;# Function Car of vehicleVehicle::Car();# Function Motorbike of vehicleVehicle::Motorbike();
BEGIN
and END
modulesPerl provides some built-in modules that include BEGIN
and END.
We use these modules to run certain pieces of code at the beginning and end of a program.
The following code snippet includes the BEGIN
and END
modules. Upon looking at the code it might seem that the print
statement inside END
would display first; but, if we run this code, it will be displayed at the end.
The code below shows how this keyword works.
BEGIN{print "Beginning of the program\n";}END{print "Ending of the program\n";}print "Begin and End modules in Perl!\n";
Free Resources