Perl module is self-contained code statements, functions, and variables that are reused by other statements.

These are similar to classes or modules in Java.

Modules are namespaces defined per file. it contains packages

How do you create a module in Perl?

Modules are reusable code functions

Let’s create a module in a file called number.pm, Extension is .pm for modules

Created a number module, the name of the package is the same as the module name.

package Number;

# Check number is positive or not

sub positive
{
    # Get given number
    $number = $_[0];

    if(    $number>0){
    return 1;
    }
    else{
        return 0
    }
}

# Check number is negative or not

sub negative
{
    # Get Given the number
    $number = $_[0];

    if($number<0){
    return 1;
    }
    else{
        return 0
    }
}

How to import the module into Perl scripts?

Once the package is defined, You need to import the module using the use keyword

Here is testNumber.pl file which imported the Number module

use Number;

print( positive(12));#1
print( negative(-12));#1

Similarly, you can also define variables in modules

package Number;

# Declare Variable
$str;

# Subroutine to display variable
sub toString
{
  print "$str\n";
}

To assign the module variable value,

use Number;
## Assign module variable
$Number::str = "Welcome";

## Call toString function
Number::toString()

Perl Module constructor and destructor

Code blocks that start with BEGIN are called constructor that is executed, during Perl script loading.

BEGIN { ... }

Code blocks that start with END are called destructors that are executed before the Perl interpreter exits the execution.

END { ... }

Require and USE keyword in module loading

Require and Use keywords are used to load the modules. The syntax is different for both

Here is an example of Require for module load

#!/usr/bin/perl

require Number;

print( Number::positive(12));#1
print(Number:: negative(-12));#1

Here is an example for use for module load

#!/usr/bin/perl

use Number;

print(positive(12));#1
print(negative(-12));#1