Home > Perl > Web programming > HTML::Mason - Initialization and Clean up Sections
HTML::Mason - Initialization and Clean up Sections
Written by Philip L Yuson   

Who is this for

This article is for those who want to learn about the Initialization and Cleanup sections of HTML::Mason code


What you should know

HTML::Mason, Perl

Introduction

We have talked about basics in HTML::Mason as well as HTML::Mason components. This article will now discuss about initiation and clean up sections.

The <%init> section

This section is given only to provide more readability to your code. It is in fact treated as a <%perl> section - only that it is executed when the script begins. You use this if you need to perform some initialization for your script.

The <%cleanup> section

This section is given only to provide more readability to your code. It is in fact treated as a <%perl> section - only that it is executed when the script ends. You use this if you need to perform some cleanup functions for your script. This is rarely used because Perl is quite efficient in cleaning up its own garbage.

Sample code

You want to open a database connection at the start of your script and get some fields from the database. Without the <%init> section, the code will look like this:

<HTML>
<HEAD></HEAD>
<BODY>
<%perl>
    my $db = DBI->connect('DBI:mysql:database=test',
            'user',
            'password');
    my $sql = "select count(client_Ndx) from Client";
    my $count = ($db->selectrow_array($sql))[0];
    if (! $count) {
</%perl>
        <B>You have no clients</B>
    % } else {
        <B>You have <% $count %> Clients</B> Woo Hoo!!!
<%perl>
}
$db->disconnect;

</%perl>
</BODY>
</HTML>

And if you have contents in your database, it will display something like this:

You have 207 Clients Woo Hoo!!!



To make this easier to read, you can do this:

<HTML>
<HEAD></HEAD>
<BODY>
<%perl>
    my $sql = "select count(client_Ndx) from Client";
    my $count = ($db->selectrow_array($sql))[0];
    if (! $count) {
</%perl>
        <B>You have no clients</B>
    % } else {
        <B>You have <% $count %> Clients</B> Woo Hoo!!!
    % }
</BODY>
</HTML>

<%init>
    my $db = DBI->connect('DBI:mysql:database=test',
            'user',
            'password');
</%init>
<%cleanup>
    $db->disconnect();
</%cleanup>

With this second style, you have separated the initiatlization and cleanup routines. It makes the code cleaner to look at.

Other Sections

Section

Description

<%once>

This section is executed only when the component is loaded (BEFORE) the <%init> section.

<%doc>

Text in this section are discarded and treated as comments

<%text>

Contents in this section are printed out as is without any substitutions.



 
Copyright: © 2017 Philip Yuson