Labels

.net (1) *nix (1) administration (1) Android (2) Axis2 (2) best practice (5) big-data (1) business-analysis (1) code re-use (1) continuous-integration (1) Cordova-PhoneGap (1) database (2) defect (1) design (3) Eclipse (7) education (1) groovy (2) https (2) Hudson (4) Java (1) JAX-RS (2) Jersey (3) Jetty (1) localization (1) m2eclipse (2) MapForce (1) Maven (12) MySQL (1) Nexus (4) notes (4) OO (1) Oracle (4) performance (1) Perl (1) PL/SQL (1) podcast (1) PostgreSQL (1) requirement (1) scripting (1) serialization (1) shell (1) SoapUI (1) SQL (1) SSH (2) stored procedure (1) STS (2) Subclipse (1) Subversion (3) TOAD (3) Tomcat (4) UML (2) unit-testing (2) WAMP (1) WAS (3) Windows (3) WP8 (2) WTP (2) XML (4) XSLT (1)

Thursday, December 2, 2010

Re-using your code with Perl modules

Re-use of code, when not copying-and-pasting, is a good thing.  I consider myself beyond a novice Perl programmer.  But since it was never a primary tool at work, I never learned how to develop re-usable Perl modules properly.  Following is a bare-bones implementation of a Perl module.  Note that a module containing a Perl class implementation would not have to use Exporter (nor should it!)

#!/usr/bin/perl
use strict;
use warnings;

package MyPkg;

require Exporter;

our @ISA = qw(Exporter);
our @EXPORT_OK = qw(myfunc);


sub myfunc{ 
 print "bar";
}


1;

In this case, the file containing this code should be named MyPkg.pm, to match the name of the package.  A bare-bones caller of this code could be as simple as:

 
#!/usr/bin/perl
use strict;
use warnings;

use MyPkg qw{myfunc};

myfunc();

Some additional notes:
  • In the module, require Exporter; is not always necessary (not yet clear the situation for its necessity)
  • If your package is something like MyGroup::MySubGroup, two things to observe:  (1) the name of your .pm file should be MySubGroup.pm and (2) the file should be placed in a subdirectory relative to @INC paths named MyGroup.  For example, if you want to locate your re-usable module togehter with your Perl script, you would put it in a subdirectory of the directory with the Perl script named MyGroup

No comments:

Post a Comment