Thursday, June 30, 2011

Writing simple perl module and using it.

package Mymodule; #Mymodule is the module name used in ur script
use strict; # This pragma forces you to declare you'r variables
use warnings;#This pragma turns on optional warnings
use base "Exporter";#The Exporter is standard module available in perl,it knows how to export functions and variables
#our module uses that export mechanism by inheriting using use base
our @EXPORT = qw(add mul $test); # our global scope. qw notation is telling perl to create a list separated by spaces
#our @EXPORT = qw(add,$sum);
#our @EXPORT = qw(mul,$mul);
#our @EXPORT = qw/sub/;
#our @EXPORT = qw($test);
our $test = 'yes';
my $sum;
my $mul;
sub add
$a = $_[0];
$b = $_[1];
$sum = $a + $b;

sub mul
$a = $_[0];
$b = $_[1];
$mul = $a * $b;

1;#This is the last line in module. Return values by which app knows module ran properly

Application to use above perl module

use Mymodule;
my $sum = add(2,3);
my $mul = mul(2,3);
print "sum is: $sum\n";
print "multiplication is: $mul\n";
if ($sum == 5)

No comments: