Learning Perl - Modules


Learning Perl - Modules


A module in Perl is a reusable piece of code that can be included in your scripts to provide additional functionality. Modules are typically used to encapsulate related subroutines, variables, and other code that can be shared across multiple scripts or applications.

Modules help in organising code, promoting code reuse, and maintaining a clean separation of concerns. They can be used to implement libraries, frameworks, or any reusable components that you might need in your Perl programs.

As your Perl programs grow in complexity, you will find that organising your code into modules can help keep things manageable. Modules allow you to encapsulate functionality and reuse code across different scripts.

A module in Perl is simply a package that contains subroutines and variables.

A package is defined using the package keyword, and it typically corresponds to a file with the same name as the package, ending in .pm. For example, a package named MyModule would be in a file called lib/MyModule.pm. It is good practice in perl to also name your modules with :: instead of camel casing and then use sub directories to organize your code. For example, a module named My::Module would be in a file called lib/My/Module.pm. however this is not a strict requirement and you can use any file name as long as you specify the correct package name in your code. You will notice that the file path is relative to the lib directory, which is a common convention in Perl projects also. The lib directory is where you typically place your custom modules. To create a package, you would start your file with the following line:

package My::Module;
1;
Enter fullscreen mode Exit fullscreen mode

This line defines a package named My::Module. The package name should match the directory structure where the file is located, so if your file is in lib/My/Module.pm, the package name should be My::Module. We also include a 1; at the end of the file, which is a common convention in Perl modules to indicate that the module has been loaded successfully. If the module does not return a true value, Perl will not load it.

We can 'use' a module in our Perl script by including it with the use statement, followed by the module name. For example:

use My::Module;
Enter fullscreen mode Exit fullscreen mode

This tells Perl to load the My::Module package, which should be located in a file named lib/My/Module.pm.

When you use a module, Perl will look for it in the directories specified in the @INC array, which includes the current directory and any directories specified by the PERL5LIB environment variable. If you have installed your module in a standard location, Perl will find it automatically. If you have not installed your module yet or installed it in a non standard location, you can add the directory to the @INC array at runtime by using the use lib pragma:

use lib 'lib';
Enter fullscreen mode Exit fullscreen mode

or by setting the PERL5LIB environment variable before running your script:

PERL5LIB=lib perl myscript.pl
Enter fullscreen mode Exit fullscreen mode

Perl also has an extensive ecosystem of modules available on CPAN (Comprehensive Perl Archive Network), which is a repository of Perl modules that you can install and use in your projects. You can search for modules on CPAN and install them using tools like cpanm or cpan. If you have never visited metacpan then I would recommend you do https://metacpan.org/, it is a great resource for finding Perl modules and documentation. In the next post we will look at how to install a CPAN module as there is one non core dependancy which will be useful going forward.

In this post we will do all steps manually, we will create a simple Perl module and use it in a script. This will give you a basic understanding of how to create and use modules in Perl. So lets create your first module in Perl, first we need to create the directory structure for our module.

mkdir My-Module
cd My-Module
mkdir -p lib/My
touch lib/My/Module.pm
touch myscript.pl
Enter fullscreen mode Exit fullscreen mode

Now, let's edit the lib/My/Module.pm file to define our module, we will do a simple 'Hello World' module that prints a message when called:

# lib/My/Module.pm
package My::Module;
use strict;
use warnings;
sub hello {
    print "Hello from My::Module!\n";
}
1;  # Return true value to indicate successful loading
Enter fullscreen mode Exit fullscreen mode

Next, let's edit the myscript.pl file to use our module:

# myscript.pl
use strict;
use warnings;
use lib 'lib';  # Add the lib directory to @INC
use My::Module;  # Use the My::Module package
My::Module::hello();  # Call the hello subroutine from My::Module
Enter fullscreen mode Exit fullscreen mode

Now, you can run your script:

perl myscript.pl
Enter fullscreen mode Exit fullscreen mode

You should see the output:

Hello from My::Module!
Enter fullscreen mode Exit fullscreen mode

This demonstrates how to create a simple Perl module and use it in a script. You can expand your module by adding more subroutines, variables, and functionality as needed.

In future posts I will show you how to export functions from your module so that you can use them without the package name, I will also cover several approaches for object orientation and how to create more complex modules with additional features like overloading of operators. For now, this should give you a good starting point for creating and using modules in Perl.

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Variables
I will attempt to explain things in this post in a way that is easy to understand, even for those who...
Learning Perl - Arrays
As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Conditional Statements
So far we have covered basic variables in Perl, today we are going to look at how to use these...
Learning Perl - Loops and Iteration
In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now...
Learning Perl - Scalars
Before moving onto more complex topics lets come back to how we represent data in Perl. The most...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...