Perl | Modules
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.
A modules name must be same as to the name of the Package and should end with .pm extension.
Example : Calculator.pm
package Calculator; # Defining sub-routine for Multiplication sub multiplication { # Initializing Variables a & b $a = $_ [0]; $b = $_ [1]; # Performing the operation $a = $a * $b ; # Function to print the Sum print "\n***Multiplication is $a" ; } # Defining sub-routine for Division sub division { # Initializing Variables a & b $a = $_ [0]; $b = $_ [1]; # Performing the operation $a = $a / $b ; # Function to print the answer 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
Examples: Test.pl
#!/usr/bin/perl # Using the Package 'Calculator' use Calculator; print "Enter two numbers to multiply" ; # Defining values to the variables $a = 5; $b = 10; # Subroutine call Calculator::multiplication( $a , $b ); print "\nEnter two numbers to divide" ; # Defining values to the variables $a = 45; $b = 5; # Subroutine call Calculator::division( $a , $b ); |
Output:
Variables from different packages can be used by declaring them before using. Following example demonstrates this
Examples: Message.pm
#!/usr/bin/perl package Message; # Variable Creation $username ; # Defining subroutine sub Hello { print "Hello $username\n" ; } 1; |
Perl file to access the module is as below
Examples: variable.pl
#!/usr/bin/perl # Using Message.pm package use Message; # Defining value to variable $Message::username = "Beginner" ; # Subroutine call Message::Hello(); |
Output:
Example:
#!/usr/bin/perl use strict; use warnings; print " Hello This program uses Pre-defined Modules" ; |
Output:
Hello This program uses Pre-defined Modules