Simple Perl Module

27 December 2020

When working on a large project, it's often useful to incorporate subroutines into a module. This page explains how to create a simple Perl module that creates simple webpage.

We'll write a calling script, MakePage.pl, and save it to our website's cgi-bin directory. The script will call the SimplePM::Webpage module, which we'll store at ./lib/SimplePM/Webpage.pm.

the calling script

Our calling script can be quite simple. All it needs to do is load the module and call the subroutines.

#!/usr/bin/perl

use strict;

use warnings;

use lib './lib/';

use SimplePM::Webpage;

print mk_header();

print mk_body("This is some sample text");

print mk_footer();

the module itself

Because we have saved our module to ./lib/SimplePM/Webpage.pm, we first declare the package name:

package SimplePM::Webpage;

We should also use the strict and warnings packages:

use strict;

use warnings;

Next, we declare the names of the subroutines that we want to include in our module. Since this example creates a webpage, we'll write one subroutine to make the page header, one to make the page body and a third to make the page footer:

require Exporter;

our @ISA = qw(Exporter);

our @EXPORT = qw(mk_header mk_body mk_footer);

Our subroutine to create the page text will take a single argument (the page text):

## make HTML body

sub mk_body {
my $intext = $_[0];
my $html;
$html .= '  <body>'."\n";
$html .= '    <p>'. $intext .'</p>'."\n";
$html .= '  </body>'."\n";
return $html;

}

The subroutine for the HTML header should first indicate that it's an HTML text file, followed by two newlines. Then it should print the HTML header itself.

## make HTML header
sub mk_header {
my $html;
$html .= 'Content-type: text/html'."\n\n";
$html .= '<!DOCTYPE html>'."\n";
$html .= '<html>'."\n";
$html .= '  <head>'."\n";
$html .= '    <title>SimplePM Webpage</title>'."\n";
$html .= '    <meta name="DESCRIPTION" content="description of this webpage">'."\n";
$html .= '    <meta name="KEYWORDS" content="perl, webpage">'."\n";
$html .= '    <meta name="Author" content="SimplePM::Webpage">'."\n";
$html .= '    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">'."\n";
$html .= '    <meta name="viewport" content="width=device-width, initial-scale=1">'."\n";
$html .= '  </head>'."\n";
return $html;

}

The footer subroutine closes the HTML file:

## make HTML footer

sub mk_footer {
my $html;
$html .= '</html>'."\n";
return $html;

}

And that closes this blog post. I hope you found it helpful.

<< back to my multilingual blog