Modules and Packages in Perl

A Perl package is a collection of code and a Perl module is a package defined in a file with the same name as that of the package name and having the .pm extension. A package lives in its own namespace. It means that two different modules may contain a function or a variable of the same name.

Declaring a Perl module

We use package to define a package in a module. A module name is same as that of the package name and has .pm extension. A module returns a true value to the Perl interpreter. This is explained after the following example. Let's declare a Perl module.

Here, the name of the file is "p.pm" and the name of the package is p. Notice that 1; is written at the end of the code. This will return a true value to the interpreter as mentioned above. We can write anything which is true in Perl instead of 1.

Using a Perl module

To use a module, we use require or use functions. We use :: to access a function or a variable from a module. Let’s look at this using an example:

Modules in different directory

If a module is present in some sub-directory, then also we use :: to tell the path of the module. For example, if a module 'b' is present in a sub-directory 'a', then we use use a::b; to load the module b. Let's see an example to understand this:

Using variable from modules

We can also use variables from different packages. But we need to declare them first before using them. We do this by use vars qw($scalar @array %hash) and we can also use our ($scalar @array %hash) with Perl v5.6.0 or higher versions. Let's use it in an example:

#p.pm is in parent directoryusestrict;usewarnings;#using package pusep;#using var_name from p$p::var_name="Sam";#Function Hello of pp::Hello();

Output

Hello Sam

BEGIN and END

BEGIN and END is used when we want to run some piece of code at the beginning and some at the end. The codes written within BEGIN{...} are executed at the beginning of the script and codes written within END{...} are executed at the end of the script. Let's see an example of this.