Related Article(s): |
Contributed by A.P. Lawrence
Print
Email
Creating Perl Modules For Web Sites
When you are writing your own code, you are more apt to
use someone else's module than write your own, unless your project gets
fairly large and complex.
Small scripting tasks just don't need the advantages modules
offer. However, there is a case where modules might make perfect sense:
web server cgi scripts often repeat the same tasks. Putting those
common features into a module can make your web scripting easier.
For example, I need to call Google's ad generating code from
just about any script that creates a page. I could just hard code it
into every script, but suppose I want to change the way it displays or
abandon Google entirely and replace the ads with something else?
Putting the code in a module other scripts can call gives me that
flexibility.
Another advantage to keeping the code separate is that I don't
have to worry about clashing variable names: variables I use in the
module won't conflict with variables in the calling script and vice
versa.
Modules aren't difficult to create:
package MyStuff;
require Exporter;
our @ISA=qw(Exporter);
our @EXPORT=qw(newad midad);
our $VERSION=1.00;
sub newad {
..
}
sub midad {
..
}
Fill in the code, and that's a working module. I have it in MyStuff.pm, and call it from any script:
#!/usr/bin/perl5
use MyStuff;
..
newad();
..
Modules do have to return a true value; you'll often see them end with "1;" to be sure of that.
That's all it takes. MyStuff.pm does have to be placed
somewhere in @INC; I put it at
/usr/local/lib//perl5/site_perl/5.8.4/MyStuff.pm
*Originally published at APLawrence.com
About the Author:
A.P. Lawrence provides SCO Unix and Linux consulting services http://www.pcunix.com

Site
Management
Index