Creating your first Perl module

Don't believe Perl is object-oriented? This article demonstrates the opposite by providing example code to get you started developing OO code with Perl.

If you write enough Perl, you'll reach a point where you need to create a module. And the more you work with quality code modules from the Comprehensive Perl Archive Network (CPAN), the more you're going to want to turn your best utility code into modules you can use the same way. This article will explain the steps involved in creating a Perl module.

Did you miss it?
Learn more about object-oriented Perl from Mark’s previous article, "Adopting good Perl OOP habits."

Why a module?
The main sign that code is worth committing to a module is easy to spot: It's code you need to use in more than one place. Making that code object-oriented is primarily a defensive action to preserve your own sanity. You want to have a well-defined interface but be able to add new things; you want to have a simple way to get and set items in your data set but still have the flexibility to rewrite it all without breaking all your old code. Object orientation provides all this. As long as you continue to support the same interface, you can tinker around inside the object any way you like.

Getting started
The first thing you want to do is create a working directory for your code. Then, create a basic module file set including the main Perl module .pm file and maybe a script and the make-file maker. Once you have a main module script file, you'll set up standard variables used by the Importer and other common things like the Perl Online Documentation headers.

This may sound like a great deal of work, but you're in luck. It also sounded like something that people would want to do over and over, so someone automated it. The automation tool is installed by default with your Perl installation. The program you are looking for is h2xs. Its original job was to help convert C program header files to Perl module code for extending Perl, but you can skip that and just have it set you up with a basic module skeleton.

The command you need to run is h2xs –ACXn MyModule, although you may want to pick a snazzier name than MyModule. The program will create a directory below the one where you run the program. The directory name will be based on the name of your module, and the program will create a few simple files in that directory. The flag ACX turns off AutoLoading. The key file we will look at is, the basic stub module file shown in Listing A.

The basics of the stub module file
You will notice the first line is a package declaration. This tells Perl that all the code following it belongs in a namespace. By default, all the code you write is in the main namespace. Thus, a subroutine called blah() would normally also be available as main::blah(). Putting the subroutines (and variables that would otherwise be global) into a namespace allows Perl to keep the is_it_blue() function from a Painter module separate from one in an Emotion module, for instance. This is how you tell Perl to protect your code and associate it with an object.

The second line in Listing A, use 5.00x;, defines the minimum version of Perl the code should be used with. You can always lower it after you test your code elsewhere, so just leave it alone for now. The usual use strict; and use warnings; are included as well. I can’t stress enough the importance of leaving those in place. Code you plan on using many places should be clean, safe code—or what is the point of making it modular?

The last section loads the Exporter and sets up some variables. The @ISA array lists other object packages that Perl should search to find methods to use on your object. Leave Exporter as the only item in the list so that the import/export methods in it will be called on your module at start time. The next three variables list items in your module that you want exported into the main package for programmer convenience. For now, leave them as they are, since you’ll probably want them later. Finally, I’d recommend bumping up the version of the code only after you get it working and start using it.

Adding your constructor
The first thing to add is a constructor method. This is a subroutine that creates and returns a new object. All it really needs to do is create a variable and return a blessed reference to that variable. In general, you’ll want to go a bit further and initialize any data you will need. This subroutine is usually called new, but that's just a convention, and there's no real need to stick to that. If you’ve ever used the DBI module for interfacing with a database, you may have noticed that its constructor is a subroutine called login.

In almost every case, you'll want to create a hashref for your object. There are likely to be values you will preset, and your constructor will probably accept some starting values, at least optionally. If you’ve been thinking along OOP lines, you probably have a subroutine for initializing your dataset already.

Teaching Perl to treat your hashref as an object is quite simple. You “bless” it with the bless command, which assures the compiler that you will trust that hash to be safe to call with your methods. There are fancier ways to use bless, but for now, make things easy on yourself and just bless your initialized object and return it.
sub new {
my $self = { INIT => 1, RED => 0, BLUE => 0, GREEN => 0 };
bless $self;

Adding your code
Adding your methods to the module is easy. Each method is merely a subroutine that knows the first argument is the object. Since you are inside your module, and you blessed any object that gets here, you can trust that it has at least been made with one of your constructors. You can even call other methods from within your module just by calling them with your object first or by actually using OO style (as in the call to green () inside set). Listing B provides an example.

Wrapping it all up
Once you add the methods you need and at least one constructor, there isn’t much left to do. Make certain your code ends with 1; so that when Perl compiles the code, the module will return a true value. That helps Perl spot when things have been loaded by mistake. Also, h2xs adds a nice documentation section to the end of your code. Use it, and everyone who ever encounters your code will thank you. Note, at least, that the default text makes fun of you for not changing it.

You can compile and install your module on most platforms with the usual perl Makefile.PL; make; make install and then test it. Or if you like, edit the script included by the h2xs script and test the module before you install it. Now, go read the handy documentation tutorial perldoc perltoot to learn more about making your own modules. There is a great deal more to OOP than just wrapping up your code in a module, but once you reach this point, you're on the right path.

Editor's Picks