Jun 28, 2013

Perl How to Export Methods

We have Exporter module in Perl :

Modules are packages but which has the capabilities of exporting selective subroutines/scalars/arrays/hashes of the package to the namespace of the main package itself.

So for the interpreter these look as though the subroutines are part of the main package itself and so there is no need to use the scope resolution operator while calling them.

It may do this by providing a mechanism for exporting some of its symbols into the symbol table of any package using it

There are times we want to export/expose methods or variables to other classes.

All these can be achieved by using module called "Exporter" module.

This is usually done like:
use Exporter;
our @ISA = ('Exporter');

Also we want to export only few methods instead of all methods, this can be achieved by
# Functions and variables which are exported by default
our @EXPORT = (multiply, $var1);

We might not want to export methods by default instead want to export on demand.
# Functions and variables which can be optionally exported
our @EXPORT_OK = (add);

Lets explain the same in detail with a class/package example :
support.pm package, it is exporting few methods
main.pl is making use of the exported methods/vars from support.pm package

support.pm

#!/usr/bin/perl

package support;

use strict;
use warnings;
use Data::Dumper;

use base qw(Exporter);  #which inturn equals to use Exporter; our @ISA = qw(Exporter);

#Exporting the add and subtract routine
our @EXPORT    = qw(multiply $var1);

#Exporting the multiply and divide routine on demand basis.
our @EXPORT_OK = qw(add);

our $var1 = 'global_var';

sub multiply {
  my $a = shift;
  my $b = shift;
 
  return ($a*$b);
}  

sub add {
  my $a = shift;
  my $b = shift;
 
  return ($a+$b);
}  

1;
  

main.pl

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

use support;          #Which is for EXPORT, export default ones (multiply, $val) by default 
use support qw(add);  #Which is for EXPORT_OK, export on demand (add on demand)

my $result = multiply(109,201);

print "\n Result after multiplication : " . $result;

print "\n Var from support.pm : " . $var1;

print "\n Result after addition : " . add(10,20);
  

Output:
 Result after multiplication : 21909
 Var from support.pm : global_var
 Result after addition : 30  



No comments:

Post a Comment