6.5
Modules and Libraries of Subroutines
As you start to build a collection of
subroutines, you'll find
that you're copying them a lot from existing programs and
pasting them into new programs. The subroutines then appear in
multiple program. This makes the listings of your program code a bit
verbose and repetitive. It also makes modifying a subroutine more
complicated because you have to modify all the copies.
In short, subroutines are great, but if you have to keep copying them
into each new program you write, it gets tiresome. So it's time
to start collecting subroutines into the handy files called
modules or libraries.
Here's how it works. You put all your reusable subroutines into
a separate file. (Or, as you keep writing more and more code, and
things get complicated, you may want to organize them into several
files.) Then you just name the file in your program and
presto: the subroutine's definitions all
get read in, just as if they were in your program. To do this, you
use the Perl built-in function use, which reads
in the subroutine library file.
Let's call this module
BeginPerlBioinfo.pm. You can put all your
subroutine definitions into it, just as they appear in the program
code. Then you can create the module by typing in the subroutine
definitions as you read the book; or, more easily, it can be
downloaded from the book's web site. But there is one thing to
remember when creating or adding to a module: the last line
in a module must
be 1; or it
won't work. This 1; should be the
last line of the .pm file, not part of the last
subroutine. If you forget this, you'll get an error message
something like:
BeginPerlBioinfo.pm did not return a true value at jkl line 14.
BEGIN failed--compilation aborted at jkl line 14.
Now, to use any of the subroutines in
BeginPerlBioinfo.pm, you just have to put the
following statement in your code, near the top (near the use
strict statement):
use BeginPerlBioinfo;
Note that .pm is left off the name on purpose:
that's how Perl handles the names of modules.
There's one last thing to know about using
modules
to load in subroutines: the Perl program needs to know where to find
the module. If you're doing all your work in one folder,
everything should work okay. If Perl complains about not being able
to find BeginPerlBioinfo.pm, give full pathname
information to the module. If the full pathname is
/home/tisdall/book/BeginPerlBioinfo.pm, then use
this in your program:
use lib '/home/tisdall/book';
use BeginPerlBioinfo;
There are other ways to tell Perl where to look for modules; consult
the Perl documentation for
use.
Beginning in Chapter 8, I'll define
subroutines and show the code, but you'll be putting them into
your module and typing:
use BeginPerlBioinfo;
This module is also available for download at this
book's web site.