Sunday, 5 March 2017

Writing a custom perl module and using it in a script

Perl offers thousands of custom modules for use in scripts via CPAN. In addition to this we can write our own perl scripts for use as modules within other perl scripts. In this article I'll demonstrate how we can write a perl module and then use it within a perl script.

First, lets write the module file. These files should have the .pm extension by default.

Here is a simple module named Speak.pm:

[root@cent68 tmp]# cat Speak.pm
package Speak;

sub test {
 print "hello there \n" ;
        }

1;


The syntax is as follows:
At the first line we include the keyword package followed by the name of our module.
At the end of the module content we must supply a return value of 1. We can write return 1 or simply 1;
I've written a simple sub routine named test. Now we'll use this sub routine in a perl script.

Now, here's our perl script:

[root@cent68 tmp]# cat test.pl
#!/usr/bin/perl -w

use Speak ;


Speak::test();


So, we'll be including our custom perl module by typing use Speak followed by a semicolon. To use a sub routine defined in our module we use the syntax <Module_name>::<sub_routine()>. This statement will in turn execute the code written in the sub routine.

Make sure that the custom module and the sub routine are present in the same directory.

When we use a module within our script the perl interpreter looks for that module in certain directories. These directory locations are contained in the @INC array variable. 

Let's examine the contents of the INC array:

[root@cent68 tmp]# perl -e 'print "@INC \n" '
/usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .
[root@cent68 tmp]#

You may notice at the end of the output a dot(.). this dot represents our current working directory. So if we have any modules present in our current working directory perl will find them.

In the article I used a trivial example to explain how we can create and use modules of our own. But using this feature we can implement some very complex functionality within our scripts.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...