A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN). These modules cover a wide range of categories such as network, CGI, XML processing, databases interfacing, etc.
Creating a Perl Module
A modules name must be same as to the name of the Package and should end with .pm extension.
Example : Calculator.pm
package Calculator;
sub multiplication
{
$a = $_ [0];
$b = $_ [1];
$a = $a * $b ;
print "\n***Multiplication is $a" ;
}
sub division
{
$a = $_ [0];
$b = $_ [1];
$a = $a / $b ;
print "\n***Division is $a" ;
}
1;
|
Here, the name of the file is “Calculator.pm” stored in the directory Calculator. Notice that 1; is written at the end of the code to return a true value to the interpreter. Perl accepts anything which is true instead of 1
Importing and using a Perl Module
To import this calculator module, we use require or use functions. To access a function or a variable from a module, :: is used. Here is an example demonstrating the same:
Examples: Test.pl
use Calculator;
print "Enter two numbers to multiply" ;
$a = 5;
$b = 10;
Calculator::multiplication( $a , $b );
print "\nEnter two numbers to divide" ;
$a = 45;
$b = 5;
Calculator::division( $a , $b );
|
Output:

Using Variables from modules
Variables from different packages can be used by declaring them before using. Following example demonstrates this
Examples: Message.pm
package Message;
$username ;
sub Hello
{
print "Hello $username\n" ;
}
1;
|
Perl file to access the module is as below
Examples: variable.pl
use Message;
$Message::username = "Geeks" ;
Message::Hello();
|
Output:

Using Pre-defined Modules
Perl provides various pre-defined modules which can be used in the Perl programs anytime.
Such as: ‘strict’, ‘warnings’, etc.
Example:
use strict;
use warnings;
print " Hello This program uses Pre-defined Modules" ;
|
Output:
Hello This program uses Pre-defined Modules
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Feb, 2019
Like Article
Save Article