This post describes Perl Modules in short or kind of notes taken from "Advance Perl Programming" book.
PERL Modules
* Modules are nothing but library packages, that can be
reused efficiently and provides a means for Modular
Programming
* Perl uses keywork 'package' to define modules and loads
predefined modules using 'use' and 'required' keywords.
To access package specific variables and function it
uses '::' notation.
* required keyword is similar like C #include, which loads
the perl file. e.g. required "myfunction.pl";
* 'use' statement is executed as soon as it is parsed. So
at compile time it is guarantee that all required modules
have been successfully loaded at compile time.
* Perl modules files using stored with extension '.pm'
reused efficiently and provides a means for Modular
Programming
* Perl uses keywork 'package' to define modules and loads
predefined modules using 'use' and 'required' keywords.
To access package specific variables and function it
uses '::' notation.
* required keyword is similar like C #include, which loads
the perl file. e.g. required "myfunction.pl";
* 'use' statement is executed as soon as it is parsed. So
at compile time it is guarantee that all required modules
have been successfully loaded at compile time.
* Perl modules files using stored with extension '.pm'
Perl Package/Module example
simple example of perl package includes variable and function
definitions. E.g. mypackage.pm
#!/usr/bin/perl
package mypackage; # same as filename
# global variables
my $space_count;
sub readspaces
{
my ($string) = (@_);
$space_count = map $_, $string =~ /\s/gs;
return $space_count;
}
sub replacespaces
{
my ($string) = (@_);
$string =~ s/\s/\#/g;
return $string;
}
1; # to avoid error "mypackage.pm did not return a true value"
# also when it is included with 'use' or 'required' module
# is expected to return a boolen success value
#!/usr/bin/perl
package mypackage; # same as filename
# global variables
my $space_count;
sub readspaces
{
my ($string) = (@_);
$space_count = map $_, $string =~ /\s/gs;
return $space_count;
}
sub replacespaces
{
my ($string) = (@_);
$string =~ s/\s/\#/g;
return $string;
}
1; # to avoid error "mypackage.pm did not return a true value"
# also when it is included with 'use' or 'required' module
# is expected to return a boolen success value
Main package and variables
In absence of explicit package declaration, perl assumes a package 'main'. The built-in variables such as $!, $_, $@, @ARGV and %ENV are belongs to package main and these are only truly global variables in Perl.
Symbolic References
Used more in Object orientation. Calling a function or variable using symbols. E.g. Calling function from package mypackage,
$mypackage::myfunction(10,20);
The symbolic reference for this above function calling is:
&{"mypackage::myfunction"}(10,20);
Package Initialization & Destruction
Use of BEGIN block does a initialization work for perl modules. The perl when it seens BEGIN block it executes right away and does further compilation later on. Simple requirement when we want to include a library before compilation, we can add below line in BEGIN block:
sub BEGIN {
use lib qw(../include); #prepends the directory to @INC
}
sub BEGIN {
use lib qw(../include); #prepends the directory to @INC
}
Similarly END block is used to do clean-up before the program exits.
Enforcing privacy
Use 'my' operator at file scope.
e.g.
package A;
my $a = 10;
package B;
print $A::a; # error, no such variable in package A
print $a # print 10
e.g.
package A;
my $a = 10;
package B;
print $A::a; # error, no such variable in package A
print $a # print 10
Define a function with 'my'
e.g.
my $rs_func = sub {
};
#call as
&$rs_func;
e.g.
my $rs_func = sub {
};
#call as
&$rs_func;
Importing Symbols
Creating namespaces and using function names or variables directly without using '::' operator. While defining the package use Exporter module insert all the package function names and variables to Exporter array. Which this inherits to the calling program. e.g.
package BankAccount;
use Exporter;
@ISA = ('Exporter');
@Exporter_OK = qw/withdraw deposite/; # or use below
# Exporter_OK states only these symbols are ok to export
@Exporter = qw/withdraw/; # this gets all the exported symbols
sub withdraw { ... }
sub deposite { ... }
1;
package BankAccount;
use Exporter;
@ISA = ('Exporter');
@Exporter_OK = qw/withdraw deposite/; # or use below
# Exporter_OK states only these symbols are ok to export
@Exporter = qw/withdraw/; # this gets all the exported symbols
sub withdraw { ... }
sub deposite { ... }
1;
# myfile.pl
#!/usr/bin/perl
use BankAccount ('deposite'); # this is analogus to
# BEGIN { require BankAccount;
# BankAccount::import('deposite');
# }
#!/usr/bin/perl
use BankAccount ('deposite'); # this is analogus to
# BEGIN { require BankAccount;
# BankAccount::import('deposite');
# }
Package nesting
Since all packages are global in scope nesting is not permitted. but one can use a directory, the '::' gets replaced with a filename separator. e.g.
use Math::Poisson; # Math/Poisson.pm
Math::Poisson::Calculate_Probability($lamda, $a);
Math::Poisson::Calculate_Probability($lamda, $a);
Autoloading
If you invoke a function called Test::func(), for example, and if func() has not been defined in module Test, Perl automatically looks for a subroutine called Test::AUTOLOAD(). If such a subroutine exists, Perl calls it with the arguments
that were passed to func(). In addition, a variable called $AUTOLOAD is set to the full name of the function that was called ("Test::func").
Usefull example is calling system with linux command
#-----------------------------------------------
package Shell;
#------------------------------------------
sub AUTOLOAD {
my($program) = $AUTOLOAD;
# We are just interested in the command name, not in
# the package name
$program =~ s/^.*:://;
system ("$program @_");
}
that were passed to func(). In addition, a variable called $AUTOLOAD is set to the full name of the function that was called ("Test::func").
Usefull example is calling system with linux command
#-----------------------------------------------
package Shell;
#------------------------------------------
sub AUTOLOAD {
my($program) = $AUTOLOAD;
# We are just interested in the command name, not in
# the package name
$program =~ s/^.*:://;
system ("$program @_");
}
#------------------------------------------------
use Shell;
ls ('-lR'); # Triggers a call to AUTOLOAD since sub ls()
# doesn't exist
mail ('-s "This is a test" joe@foo.com < letter.txt');
use Shell;
ls ('-lR'); # Triggers a call to AUTOLOAD since sub ls()
# doesn't exist
mail ('-s "This is a test" joe@foo.com < letter.txt');
Accessing Symbol table
Dumping a package symbol table using stashing the function e.g. function name foo can be accessed by a hash %foo
TODO
Questions on perl modules/packages
1. How do you make variables public, private, or protected in Perl?
use 'my' for private and 'our' keyword for public
use 'local' might bring protected version
2. use vs require keyword. How to create module
Use and Require are most common methods used to load modules.
Use:
1) It is evaluated at compile time only.
2) it is used only to load modules.
3)No need to give file extensions when we are using "use"
Require:
1)This is evaluated at Run time
2)This method is used for both libraries and modules.
3)Need to give file extensions like pl,pm etc..
3. List the programming guidelines that must be followed when programming
with Perl modules
* The Module and the package name must be the same.
* The only allowable package name needs to have the extension “.pm”
* The package must be derived from the exporter class when no
object-oriented technique is used
No comments:
Post a Comment