Tuesday, October 24, 2006

Perl: Own module with my common functions

Lately, I also needed to create one file containg some of my functions that I use in many Perl programs. First my thought was to create some library or module, that I will include in my programs using just use key word.

I dicided to do my own package, and here I will present some more or less what I have fastly done to get what I wanted.

First I create module. The code goes in the file named MyModule.pm within the directory Utilities: that is, Utilities/MyModule.pm

  1. package Utilities::MyModule;
  2. use Exporter;
  3. @ISA = qw(Exporter);
  4. @EXPORT = qw(&myFun1 &myFun2);

  5. sub myFun1 {
  6. print "Some action of myFun1";
  7. }
  8. sub myFun2 {
  9. print "Some action of myFun2";
  10. }
  11. 1;
Line 1 declares the package that the module will put its global variables and functions in.

Line 4 assigns the list (&myFun1 &myFun2) to the special, per-package array @EXPORT. When someone imports this module, variables and functions listed in that array are aliased into the caller's own package. That way they don't have to call the function Utilities::MyModule::myFun1() after the import. They can just write shuffle(23) instead. This won't happen if they load Utilities::MyModule with require Utilities::MyModule; only a use imports.

Lines 5 and 8 set up the package global functions to be exported.

Finally, line 11 is a simple 1, indicating the overall return value of the module. If the last evaluated expression in the module doesn't produce a true value, an exception will be raised.

After creating this module, you can import it simply by:
use Utilities::MyModule;