3.2.2. Exporting and Importing Functions
It is possible to make a functions of your module automatically available in any other namespace or script that uses it. To do so one needs to type the following code fragment near the beginning of the module:
use Exporter; use vars qw(@ISA @EXPORT); @ISA=qw(Exporter); @EXPORT=("function1", "function2", "function3");
What this fragment does is make the module inherit the Exporter
module which is a special Perl module that can export symbols. Then it declares the special variable @EXPORT
which should be filled with all the functions that one wishes to export.
Here is an example which has a module called "Calc" and a script that uses it:
# File: Calc.pm # package Calc; use strict; use warnings; use Exporter; use vars qw(@ISA @EXPORT); @ISA=qw(Exporter); @EXPORT=("gcd"); # This function calculates the greatest common divisor of two integers sub gcd { my $m = shift; my $n = shift; if ($n > $m) { ($m, $n) = ($n , $m); } while ($m % $n > 0) { ($m, $n) = ($n, $m % $n); } return $n; } 1;
#!/usr/bin/env perl use strict; use warnings; use Calc; my $m = 200; my $n = 15; print "gcd($m,$n) == " , gcd($m,$n), "\n";
As you can see, the script invokes the "gcd" function of the "Calc" module without having to invoke it with Calc::gcd()
. Exporting functions like that should be used with care, as the function names may conflict with those of the importing namespace.