Good design does not stop with the use
of subroutines. Often, several different scripts will be
designed to incorporate the use of similar routines. In this
case, it makes sense to remove the common routines from the
programs and place them in a separate file of routines.
This file can then be loaded as a
library of subroutines into each program as needed.
For example, in CGI, most applications
will need a form gathering and parsing routine, a template for
sending out the HTTP header, and perhaps one to generate
template HTML code, such as the following:
<HTML><HEAD><TITLE>My Script
Title</TITLE></HEAD><BODY>
In this case, we use library files and
require them from the main script. A library file in Perl is
simply a text file containing subroutines that are shared by
several different Perl scripts. For these library files to be
usable by the program, they must be readable by the script and
must be in the Perl library path (or its location must be
explicitly referenced).
For example, if we wanted to load
Steven Brenner's cgi-lib.pl library into our script, we would
use the following:
require "cgi-lib.pl";
When this is done, every subroutine in
cgi-lib.pl becomes accessible to the main script as if it were
actually written into the script's code. We simply reference a
subroutine contained in cgi-lib.pl as we would any other
subroutine in the main program.