1 Perl modules(libraries)

1.1 Modules

A (Perl) module is a Perl script stored in a file by itself and named "packagename.pm". The last executed line in a module must be return 1;. A package can be used in a different file by including use packagename; at the beginning of the file. Examples of modules are CGI.pm and IO.pm. The path for modules is stored in the @INC array. Directories can be added to this path via the PERL5LIB environment variable or via use lib '/home/username/somedirectory'.

1.2 Exercises

1) Create a module called 'Hello.pm' and save it in a directory 'perl_lib' under your home directory. Write a subroutine called 'sayhello' within Hello.pm, which prints "Hello World". Write a perl script in a different directory that uses this subroutine.

1.3 CPAN

A large set of freely available modules (or libraries) exist for Perl at CPAN (see CPAN). If a module does not already exist in a local installation, it can be downloaded from CPAN. The command for downloading and installing modules is
perl -MCPAN -e 'install MODULENAME'.
(If you do not have root access to the machine, you'll need something like
perl Makefile.PL LIB=/home/username/somedir PREFIX=/home/username/somedir
make test
make
make install
where "username" is your username and "somedir" is some directory. You may also need to set the PERL5LIB environment variable to your local directory, but you can try it without first.

Modules exist for almost everything, such as database connections, HTML parsing (HTML.pm, LWP.pm), operating system specific features, networking, mail, encryption, language processing and graphics. Most of the modules use object-oriented Perl (see week 12).

1.4 Exercises

2) Have a look at CPAN. You can browse through the modules at CPAN Search. Can you find the CGI::Session module? Can you find out from the FAQ, how to check for locally installed modules?

2 DBI

Perl modules for databases normally consist of two parts: a database independent interface (DBI.pm) and a database specific database driver (DBD.pm for generic use; Mysql.pm for Mysql; Pg.pm for Postgres, Oracle.pm for Oracle etc).

Database interfaces support the following tasks:

  • connect to the database,
  • prepare a query (as a string),
  • execute the query,
  • fetch the results (either row by row or as an array)
  • finish the query (so that the database can clean up its buffers, this is optional)
  • disconnect from the database

    Below are examples for accessing a Mysql database (without or with HTML Templates) and for Postgres. There are no exercises for this section because not all students have database accounts.

    2.1 Mysql without HTML Templates

    Note: This example expects a database called "yourdb" for a user "u123", a password "password" and a table "this_table".

    #!/usr/local/bin/perl -w
    ########################
    use CGI qw(:standard -debug);
    use Mysql;
    use DBI;
    ########################
    print header();
    print <<EOS;
    <html>
    <head> <title>DB</title> </head> <body>
    EOS

    $db = DBI->connect('dbi:mysql:yourdb;host=zeus.napier.ac.uk', 'u123', 'password') || die "Cannot connect to database";
    $query = $db->prepare( qq { SELECT * from this_table;} );
    $query->execute();

    print "<table border=1> <tr>";
    foreach $i (@{$query->{NAME}}) {
    print "<th> $i ";
    }
    while (@row = $query->fetchrow()) {
    print "<tr>";
    foreach $col (@row) {
    if ($col eq "") { $col = ' '; }
    print " <td>$col ";
    }
    print "<br>\n";
    }
    $db->disconnect;

    2.2 Mysql with HTML Templates

    Note: This example expects a database called "yourdb" for a user "u123" and a password "password". The database has two columns: name and job in a table this_table.

    #!/usr/local/bin/perl -Tw
    ####################################################################
    use CGI qw(:standard -debug);
    use HTML::Template;
    use Mysql;
    use DBI;

    ####################################################################
    my $template_text = <<EOS;
    <html>
    <head><title> Database</title>
    </head><body>

    The Database results are:<p>

    <table border=1>
    <tr><th>Name <th>Job
    <TMPL_LOOP NAME="EMPLOYEE_DATA">
    <tr><td><TMPL_VAR NAME="name"> <br>
    <td><TMPL_VAR NAME="job"> <p>
    </TMPL_LOOP>
    </table>
    EOS

    ################## CGI and Template start #########################
    my $cgi = CGI->new();
    my $template = HTML::Template->new(scalarref => \$template_text );
    print $cgi->header();

    ###################### Database commands ###########################
    $db = DBI->connect('dbi:mysql:yourdb;host=zeus.napier.ac.uk', 'u123', 'password') || die "Cannot connect to database";
    $query = $db->prepare( qq { SELECT * from this_table;} );
    $query->execute();
    while ($row = $query->fetchrow_hashref()) {
    push(@loop_data, $row);
    }
    $db->disconnect;

    ################## Template is printed to browser ################

    $template->param(EMPLOYEE_DATA => \@loop_data);
    print $template->output();

    2.3 Postgres

    #!/usr/local/bin/perl

    use CGI;
    use Pg;

    $db = Pg::connectdb("dbname = user");

    $column = param("value1");
    $query = "Select $column from test";
    $result = $db->exec($query);

    for ($i = 0; $i < $result->nfields; $i++) {
          print $result->fname($i);
    }

    for ($i = 0; $i < $result->ntuples; $i++) {
          for ($j = 0; $j < $result->nfields; $j++) {
                print $result->getvalue($i, $j);
          }
    }

    3 Graphics

    Perl modules exist for VRML, Flash and Scalable Vector Graphics (SVG). SVG is a graphics standard that has been suggested by the W3C during the last few years. It facilitates creation of vector graphics which can be incorporated into HTML files but in contrast to Flash (which is binary), SVG uses XML. SVG is ideal for Perl/CGI pages, but unfortunately so far only a subset of SVG is cross-platform compatible. Currently SVG can only be viewed using plug-ins. In the JKCC you should be able to install an SVG viewer from the menu.

    (If you want to install a free SVG viewer on your home computer you can find one on this page. As far as I know, both the Adobe Viewer and the Java-based Batik/Squiggle SVG browser are reasonably good at displaying SVGs. I have heard rumours about the Adobe viewer causing problems with IE or the windows registry. Not sure if that's true - but you might want to read about possible problems on the WWW before installing it.)

    The following example reads a color parameter from a form and then paints a circle in that color.

    #!/usr/local/bin/perl -w
    use SVG;
    use CGI qw(:standard -debug);

    my $color = param("color");

    # the next line should be uncommented for some security checking
    # if ($color !~ /^\w+$/) {die;}

    # create an SVG object
    my $svg= SVG->new(width=>200,height=>200);

    # draw a circle at position (100,100) with ID 'this_circle'
    # which is filled in $color
    $svg->circle(id=>'this_circle',cx=>100,cy=>100,r=>50, style =>{fill =>"$color"});

    # create and print the SVG code
    print "Content-type: image/svg+xml\n\n";
    my $out = $svg->xmlify(-dtd => 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd');
    print $out;

    3.1 Exercises

    3) Try the SVG example. (If SVG.pm is not installed, you need to first download it from CPAN and install it.) Create a form which asks a user for a colour. The SVG CGI script will then draw a circle in that colour.

    4 Information Architecture and Design

    While so far all of this tutorial has been devoted to Perl, it should be pointed out that professional server-side web programming has many more aspects apart from the coding of the scripts. Some aspects (such as security) were discussed in this tutorial. Other aspects (such as debugging, testing and documentation) are standard software engineering practice. Last but not least, some aspects (such as HCI and information architecture) should be standard practice but, in fact, are often underestimated. Information architecture in particular is not yet very well known.

    "Information architecture is the art and science of structuring and organising information environments to help people achieve their goals" (Argus, 2000). Information architecture attempts to balance the technical requirements with user requirements and information system requirements. Some examples where information architecture can help are:

  • Systems analysis techniques can be applied to information design.
  • A variety of common practices (such as use of metaphors, common elements of websites) can be identified and gathered in informal guidelines.
  • Example: While it may be technically sensible to store the content of a large website in a database, it may not be best for users if the whole website has the look and feel of a database interface.
  • Example: Search engines must overcome the differences between the logical Boolean operators (AND, OR, NOT) and the common sense, natural language uses of operators in searches.
  • Example: Shopping carts: see the Argus white paper.