Section B.4. Extending Perl s Functionality

B.4. Extending Perl's Functionality

One of the most common pieces of good advice heard in the Perl discussion forums is that you shouldn't reinvent the wheel. Other folks have written code you can put to use. The most frequent way to add to what Perl can do is by using a library or module. Many come with Perl and others are available from CPAN. You can even write your own libraries and modules.

B.4.1. Libraries

Many programming languages offer support for libraries much as Perl does. Libraries are collections of (mostly) subroutines for a given purpose. In modern Perl, though, it's more common to use modules than libraries.

B.4.2. Modules

A module is a "smart library." A module will typically offer a collection of subroutines that act as if they were built-in functions, for the most part. Modules are smart in that they keep their details in a separate package, only importing what you request. This keeps a module from stomping on your code's symbols.

Though many useful modules are written in pure Perl, others are written using a language like C. For example, the MD5 algorithm is like a high-powered checksum.[*] It uses a lot of low-level bit twiddling that could be done in Perl but hundreds of times more slowly;[] its an algorithm that was designed to be efficiently implemented in C. So, the Digest::MD5 module is made to use the compiled C code. When you use that module, it's as if your Perl had a built-in function to calculate MD5 digests.

[*] It's not a checksum, but that's good enough for this explanation.

[] The module Digest::Perl::MD5 is a pure Perl implementation of the MD5 algorithm. Though your mileage may vary, we found it to be about 280 times slower than the Digest::MD5 module on one sample dataset. Many of the bit twiddling operations in the C algorithm compile down to a B.4.3. Finding and Installing Modules

Maybe your system already has the module you need. But how can you find out which modules are installed? You can use the program inside, which should be available for download from CPAN in the directory

If none of the available modules on your system suit your needs, you can search for Perl modules on CPAN at To install a module on your system, see the perlmodinstall manpage.

When using a module, you'll generally put the required use directives at the top of your program. That makes it easy for someone who is installing your program on a new system to see at a glance which modules it needs.

B.4.4. Writing Your Own Modules

In the rare case that there's no module to do what you need, an advanced programmer can write a new one, in Perl or in another language (often C). See the perlmod and perlmodlib manpages for more information. The Alpaca covers how to write, test, and distribute modules.

Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: