Packages in Perl
A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained in any package belongs to the main package. Therefore, all the variables being used, belong to the ‘main’ package. With the declaration of additional packages, it is maintained that variables in different packages do not interfere with each other.
Example : Calculator.pm
package Calculator; # Defining sub-routine for Addition sub addition { # Initializing Variables a & b $a = $_ [0]; $b = $_ [1]; # Performing the operation $a = $a + $b ; # Function to print the Sum print "\n***Addition is $a" ; } # Defining sub-routine for Subtraction sub subtraction { # Initializing Variables a & b $a = $_ [0]; $b = $_ [1]; # Performing the operation $a = $a - $b ; # Function to print the difference print "\n***Subtraction 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 add" ; # Defining values to the variables $a = 10; $b = 20; # Subroutine call Calculator::addition( $a , $b ); print "\nEnter two numbers to subtract" ; # Defining values to the variables $a = 30; $b = 10; # Subroutine call Calculator::subtraction( $a , $b ); |
Output:
Examples: Test_out_package.pl outside Calculator directory
#!/usr/bin/perl use GFG::Calculator; # Directory_name::module_name print "Enter two numbers to add" ; # Defining values to the variables $a = 10; $b = 20; # Subroutine call Calculator::addition( $a , $b ); print "\nEnter two numbers to subtract" ; # Defining values to the variables $a = 30; $b = 10; # Subroutine call Calculator::subtraction( $a , $b ); |
Output:
#!/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 = "ABC" ; # Subroutine call Message::Hello(); |
Output:
#!/usr/bin/perl # Predefined BEGIN block BEGIN { print "In the begin block\n" ; } # Predefined END block END { print "In the end block\n" ; } print "Hello Perl;\n" ; |
Output:
In the begin block Hello Perl; In the end block