Sunday, April 19, 2009

Creating and Using Perl modules

A little example to demonstrate how to create and use Perl module in Perl application.

First we will create the module:

The module file extension should be “pm”, and it should contains:
#MODULE_START
# Module Name
package Comm;
#######################################################################
## Module related arguments

use 5.006;
## Constructor
sub new {
    my $package = shift;
    return bless({}, $package);
}

#######################################################################3
## My Code

sub printHello()
{
    print "Hello World";
}

#MODULE_END

Now, Lets use the module in our Perl application
#APP_START
#/usr/bin/perl;
use strict;
use warnings;
# My Module
use Comm;

# Module creation
my $myModule= Comm->new;
$
myModule->printHello;

#APP_END

Few Notes about this sample:

  1. The application should know the module path.

  2. As you can see, I'm calling the module function with the module prefix (Conn->....), To avoid it we can use the “Exporter” inside the module to export its function directly,









No comments: