What are packages and modules in Perl?

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.

Code

Perl package

A package name must always be at the start of a Perl program.

Consider the following code syntax with two subroutinesblocks of code that can be reused across programs. (Car and Motorbike), and a Vehicle package at the top of the code file.

# Package definition
package Vehicle;
sub Car{
print "This is a car subroutine!\n";
}
sub Motorbike{
print "This is a motorbike subroutine!\n";
}

Perl module

The following example shows how to import a package into our code file with the use keyword.

# Using package Vehicle
use Vehicle;
# Function Car of vehicle
Vehicle::Car();
# Function Motorbike of vehicle
Vehicle::Motorbike();

Perl BEGIN and END modules

Perl 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

Copyright ©2025 Educative, Inc. All rights reserved