Home > Perl > Web programming > HTML::Mason: Embedding Perl in HTML
HTML::Mason: Embedding Perl in HTML
Written by Philip L Yuson   

Who is this for
This article is for those who are looking for Perl equivalent of PHP or jsp.

What you need to know
Perl programming, HTML, Apache administration

The growing trend in website development these days is to embed Perl code with the HTML code. This is seen with the popularity of PHP and jsp. Years ago, using CGI was sufficient to generate DHTML. Unless another module is used to separate the HTML from the logic, debugging the script is difficult and tedious. The script has to take care of 'print'-ing the HTML.

With HTML::Mason, the Perl script is embedded in the HTML code. This means that the HTML skeleton is coded and logic code is written only in portions of the script that needs it.

Installing HTML::Mason
HTML::Mason works with Apache 1.3 with mod_perl in native mode. On Apache 2.0 and mod_perl 2.0, HTML::Mason runs in CGI mode.

Installation instructions for HTML::Mason on for Apache 1.3 and mod_perl 1.0 is straightforward. Before installing HTML::Mason, make sure that mod_perl is already installed on Apache. Download the module from CPAN or from the HTML::Mason website.

Do a :

perl Makefile
make && make test && make install

Once installed, you will need to configure the Apache server. Edit the httpd.conf file and make sure you include this:

PerlModule HTML::Mason::ApacheHandler
<Location /usr/local/apache/htdocs/mason>
SetHandler perl-script
PerlHandler HTML::Mason::ApacheHandler

You can also use the Directory or Files directive to make HTML::Mason work in specific directory or files.

Installation instructions for HTML::Mason on Apache 2.0 and mod_perl 2.0 are available at:  http://beaucox.com/mason/mason-with-apmp...

Sample HTML::Mason Code
If you want to generate a code to show the date today, you can do this:

use Date::Calc;
my @today  = Date::Calc->Today();
my $str = "$today[0]-$today[1]-$today[2]";

Today is <%$str %>

Notice that the Perl code is embedded in the HTML page. Perl code is executed when the interpreter encounters a <%perl>. Perl code ends when the interpreter encounters a </%perl>.

Likewise, notice that you can also have a variable called $str printed with the HTML by escaping it with a <% %>.

If you want to learn more about HTML::Mason, you can check the documentation that comes with the module. or visit the HTML::Mason website.

Copyright: © 2017 Philip Yuson