Perl Modules

  • A Perl module is a reusable collection of related variables and subroutines that perform a set of programming tasks. 
  • There are a lot of Perl modules available  on the Comprehensive Perl Archive Network (CPAN). 
  • You can find various modules in a wide range of categories such as network, XML processing, CGI, databases interfacing, etc.
Example:
We have one FileLogger module (FileLogger.pm) which performs logging and we will see how we can use it in our program.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package FileLogger;
# FileLogger.pm
 
use strict;
use warnings;
 
my $LEVEL = 1; # default log level
 
sub open{
   my $logfile = shift;
   # open log file for appending
   open(LFH, '>>', $logfile) or die "cannot open the log file $logfile: $!";
   # write logged time:
   print LFH "Time: ", scalar(localtime), "\n";
}
 
sub log{
   my($log_level,$log_msg) = @_;
   # append log if the passed log level is lower than
   # the module log level
   if($log_level <= $LEVEL){
      print LFH "$log_msg\n";
   }
}
 
sub close{
   close LFH;
}
 
sub set_level{
   # set the log level
   my $log_level = shift;
   # check if the passed log level is a number
   if($log_level =~ /^\d+$/){
      $LEVEL = $log_level;
   }
}

Let’s see a following program that uses the FileLogger module:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/usr/bin/perl
use strict;
use warnings;

#use statement to load the FileLogger module. 
use FileLogger;
 
# Call the subroutines in the FileLogger module using syntax  module_name::subroutine_name
FileLogger::open("logtest.log");
FileLogger::log(1,"This is a test message");
FileLogger::close();

In above example, we used a use statement to load the FileLogger module. Later we called the subroutines in the FileLogger module using syntax  module_name::subroutine_name.


What is the difference between use and require in Perl?
Use: It is used only for the Perl modules. The included modules are verified at the time of compilation. It does not need file extension.

Require: It is used for both Perl modules and libraries. The included objects are verified at run time. It does need file extension.


<-- Previous || Next -->

2 comments: