PerlWiz - Web Programming

Click here for the perlwiz.biz documentation home page
Contents Prior Page Next Page

On this page, we will look at some of the ways that PerlWiz can help you develop web applications in Perl, using a worked example to help illustrate this.

Creating a new temporary file

A good place to start when creating a new program is to try a few things out in a new temporary program. To do this:-

Using a Code Template to create a HTML outline document

A useful place to start is to add the basic skeleton of a HTML document. For this, we will use a code template.  This is a code snippet which contains a useful bit of code that you may wish to reuse quickly and easily.  You can have as many code templates as you like.  The standard PerlWiz program comes with over seventy of these, which you can amend, add to, search, or rearrange using the Templates | Organize Code Templates menu option or the Ctrl+F6 key combination.

The code template we are interested in can be inserted at the current cursor position (make sure the cursor is a few lines below the #!/usr/bin/perl shebang line) using one of the following methods:-

Notice that the shorthand name (known as the Alias) appears next to the menu option in brackets.

If you wish to try both, then try the first, and undo it by pressing Ctrl+Z or by choosing the Edit | Undo menu option or by clicking on the icon on the toolbar. Then you can try the second method.

The program should now look something like this:-

#!/usr/bin/perl

Content-type: text/html\n\n
<!DOCTYPE HTM PUBLIC "-//IETF//DTD HTML//EN">
<html>

  <head>
    <title>Outline Document Title</title>
  </head>

  <body bgcolor="#ffffff">
    <h1>Sample Heading</h1>
    <p>Sample paragraph<br>Second line in paragraph
    </p>
  </body>

</html>

Converting text to print statements

The text we inserted was HTML, which cannot be placed directly into a Perl program. It needs to be output to the console using one or more print commands. There are two ways of doing this - using a where block, and using a series of print statements. You can use whichever method you find preferable.  First, highlight all of the line in the HTML that you just inserted into the program, then:-

The first option would produce the following program:-

#!/usr/bin/perl

print <<_EOT;
Content-type: text/html


<!DOCTYPE HTM PUBLIC "-//IETF//DTD HTML//EN">
<html>

  <head>
    <title>Outline Document Title</title>
  </head>

  <body bgcolor="#ffffff">
    <h1>Sample Heading</h1>
    <p>Sample paragraph<br>Second line in paragraph
    </p>
  </body>

</html>
_EOT

This uses a print where block - everything between the print <<_EOT; line and the line with _EOT on its own will be sent to  STDOUT (i.e. the console), which gets passed to your web server, which will then pass the text onto your browser.

The second option would produce the following program:-

#!/usr/bin/perl

print "Content-type: text/html\n\n";
print "<!DOCTYPE HTM PUBLIC \"-//IETF//DTD HTML//EN\">\n";
print "<html>\n\n";
print "  <head>\n";
print "    <title>Outline Document Title</title>\n";
print "  </head>\n\n";
print "  <body bgcolor=\"#ffffff\">\n";
print "    <h1>Sample Heading</h1>\n";
print "    <p>Sample paragraph<br>Second line in paragraph\n";
print "    </p>\n";
print "  </body>\n\n";
print "</html>";

Try executing either of these methods by clicking on the button. This will show the HTML output in the print statement(s) with context highlighting. Try clicking on the button to see this rendered in the default browser.

Changing the colo(u)r of the html document's background

Notice that the background is white. What if wanted a different colour as the background?  PerlWiz has an easy-to-use feature that lets you change a colour in HTML text interactively:-

In this case, choose the yellow colour from the drop down list. Now choose the ellipses (...) button and select the Define Custom Colors>> button. Slide the vertical slider on the right-hand side upwards to make the yellow colour lighter. Click OK button to preview the colour in the oval, and see the colour number / name in the text box. Finally, click on OK to use the colour in your HTML. The #ffffff will change to your new colour number.

Click on the Browser Output tab or click on the button to see the effect of this change in the browser.

Using a Code Template to create a form

Let's create a form with three fields:-

We can insert a form inside the body section of the HTML by placing the cursor just before the closing </body> tag and press the new-line or Enter key to insert a blank line. Move the cursor so that it is on the blank line. Now use the code template for forms - You can access this by one of the following two methods:-

If you used a series of print statements instead of one single print statement, then you will also need to convert this to print statements (or if you prefer, a single print statement this time) as described before. 

Assuming that we are working from a single print statement, the program should look something like this:-

#!/usr/bin/perl

print <<_EOT;
Content-type: text/html

<!DOCTYPE HTM PUBLIC \\"-//IETF//DTD HTML//EN\\">
<html>

  <head>
    <title>Outline Document Title</title>
  </head>

  <body bgcolor=\\"#ffffff\\">
    <h1>Sample Heading</h1>
    <p>Sample paragraph<br>Second line in paragraph
    </p>
    <FORM ACTION="/cgi-bin/myform.cgi" METHOD="POST">
      <INPUT TYPE="submit" VALUE="Submit Data">
      <INPUT TYPE="reset" VALUE="Clear Data">
    </FORM>
  </body>

</html>
_EOT

If you try executing your program now using the button, you will see two buttons have appeared - the submit and reset button.

Add a form text box

Let's add a name field now. Insert a blank line above the first <INPUT> field, and do one of the following:-

This gives us a text form field called name with a heading of Name: and a maximum length of 40.  We could change any of these attributes if we liked.

Type out <BR> at the end of the line to give us:-

Name: <INPUT TYPE="text" NAME="name" SIZE=40><BR>

and try the program again by clicking on the button.

Add a form drop-down list

Next, we will add a drop-down list of payment methods - i.e. Mastercard or Visa in this case. We will make the default Mastercard.

Insert a blank line below the Name text field line (after the <BR> line break).

We will now insert a drop-down <SELECT> list - use either of the following methods:-

This shows three options in a <SELECT> list. Replace the text Option 1 with the text Mastercard - note that this is already selected as default. Replace the text Option 2 with the text Visa. Delete the third option line, as only two selections are required at this time.

Now replace the name drop_down with pay_method

To the left of the <SELECT> tab, type a heading such as Payment Method: and after the closing </SELECT> tab, add a line break <BR>

The select lines should look something like this:-

Payment Method: <SELECT NAME="pay_method" SIZE=1>
<OPTION SELECTED>Mastercard</OPTION>
<OPTION>Visa</OPTION>
</SELECT><BR>

Try the program again by clicking on the button. You should have a new drop-down list with two payment options.

Add a form checkbox

Next, we will add a checkbox to decide whether the visitor wishes to receive promotional offers or not.

Insert a blank line below the last  </SELECT> line.

We will insert a checkbox using a code template using any of the two following methods:-

Replace the text Do Something with the text Receive future promotional Offers?<BR>

Replace the name do_it with offers.

The line should look something like this:-

<INPUT TYPE="checkbox" NAME="offers" VALUE="yes" CHECKED> Receive future promotional offers?<BR> 

Try the program again by clicking on the button.  You should see a pre-checked checkbox with the appropriate question next to it.

Processing form results

When the Submit button is pressed, the details of the form fields will be submitted, identified by their names. At the moment, they will be submitted to a program expected to be found at location /cgi-bin/myform.cgi

This does not exist. Let's change this location so that the Perl program that displays the form is the same program that processes the form.  This is a common technique.

First, let us save the program that we have so far as a non-temporary file by clicking on File | Save As... or Ctrl+S. Save the file under the projects directory under the name myform.cgi, as described in the first steps tutorial.

Most web servers recognize a program ending with .cgi as a perl program, although some use .pl as their preferred ending.

Now, change the form location from /cgi-bin/myform.cgi to just myform.cgi

The first form line should now read:-

<FORM ACTION="myform.cgi" METHOD="POST">

Note that the POST method will submit data as STDIN input into your program via the main body of the request sent to the web server, whereas the GET method will submit data as part of the URL used to identify where the form data is to be sent to the web server - i.e. onto the end of myform.cgi - in most browsers, this makes the data visible just by looking in the address bar.

Next insert a new line between the shebang line (first line in the program) and the print statement that follows.

We will insert a piece of code that will retrieve the form parameters using another code template.  Use one of the following methods:-

Remove the following lines - they are only needed when looking at a multi-value field (e.g. a multi-value listbox, or several checkboxes with the same name but different values when checked).

@options = $q->param('options');
foreach $option (@options) {
print "option: $options\n";
}

Remove the closing curly brace (just before the print line for the HTML form), and move the cursor to the end of the document (using Ctrl+End).

Insert a closing curly brace } at the end of the program to replace the one previously deleted.  Don't be tempted to indent the text in the block of print lines - remember that they are to be output 'as-is' which would include indentation. The closing _EOT also need to be flush against the left margin.

Now add another two lines to read the other form field values, and a further three lines to display the results as follows:-

$name = $q->param('name');
$pay_method = $q->param('pay_method');
$offers = $q->param('offers');

print "Content-type: text/html\n\n";
print "<html><head><title>Results</title></head><body><pre>";
print "Name: $name\nPay Method: $pay_method\n";
print "Offers? $offers\n</pre></body></html>";

These could really do with being indented between the curly braces.  To do so, highlight all lines completely that need to be indented, and do one of the following three options:-

The final program should look something like this:-

#!/usr/bin/perl

use CGI qw/:standard/;

$q = new CGI;

if ($q->param())
{
  $name = $q->param('name');
  $pay_method = $q->param('pay_method');
  $offers = $q->param('offers');

  print "Content-type: text/html\n\n";
  print "<html><head><title>Results</title></head><body><pre>";
  print "Name: $name\nPay Method: $pay_method\n";
  print "Offers? $offers\n</pre></body></html>";
}
else
{
print <<_EOT;
Content-type: text/html

<!DOCTYPE HTM PUBLIC \\"-//IETF//DTD HTML//EN\\">
<html>

  <head>
    <title>Outline Document Title</title>
  </head>

  <body bgcolor=\\"#ffffff\\">
    <h1>Sample Heading</h1>
    <p>Sample paragraph<br>Second line in paragraph
    </p>
    <FORM ACTION="myform.cgi" METHOD="POST">
      Name: <INPUT TYPE="text" NAME="name" SIZE=40><BR>
      Payment Method: <SELECT NAME="pay_method" SIZE=1>
        <OPTION SELECTED>Mastercard</OPTION>
        <OPTION>Visa</OPTION>
      </SELECT><BR>
      <INPUT TYPE="checkbox" NAME="offers" VALUE="yes" CHECKED> Receive future promotional offers?<BR> 
      <INPUT TYPE="submit" VALUE="Submit Data">
      <INPUT TYPE="reset" VALUE="Clear Data">
    </FORM>
  </body>

</html>
_EOT
}

Check the syntax using the button.

Entering form parameters - GET and POST

If all seems OK, try executing the program, You should get the form displayed. Notice that unless you have a web server active on your local PC (or the PerlWiz Web Server turned on - click on the button to switch this on and off), then you cannot submit the data using the submit button.  For more details on setting up the PerlWiz web server (required if you have saved the program anywhere except in the default project directory), see the Web Server part of the reference page.

Instead of having to type out data into a form every time we wish to test a form, we can instead simulate the submission of forms using the Params tab at the left hand side of the edit window.

We use this screen to list the parameters that are to be passed into the Perl program as if form fields had been filled in (either from the same Perl program, or from any other source).

There are two send types we can use to pass data in - Get and Post. Get passes data using data tagged onto the end of the URL as & separated name/value pairs. Post passes data in the body of the request in a similar format, but does not show in a browser's address bar, and is not typically restricted in size as much as a Get request.

We select which method we wish to use using the Form Send Type radio box. Note that the Get + Post option send data in both ways simultaneously (this would not happen normally) in case you wish to test that both ways work OK.  The post method would be the one picked up by the CGI library in this case.  If we do not want to send any data, we can disable this by choosing the None option here.

To simulate entry of the text Simon Huggins into the text field that we called name, we would add a new form field by clicking on the button. Under Form Field Name, enter the name name and then press the Tab key to move to the Form Field Data, and enter the value for the field, Simon Huggins in this case. Notice this appears in the listbox with a tick next to it. The tick means the field will be sent to the program when it is executed (so long as Form Send Type is not None). Click on the tick to ensure the field data will not be sent. This allows you to add several different versions of the same field, and tick the version that you want according to what you are trying to test.

In this case, we will leave the item intact.

Add two more form fields, one called pay_method with a value of Visa and another called offers with a value of yes.

If you wish to delete any of the fields at any time, just click on the field in the list box, and click on the button.

The list box should look something like this when you have finished:-

Test in Text and Browser views

Test entry of data into the form using these values by clicking on the button. You should get a result something like this:-

Name: Simon Huggins

Pay Method: Visa

Offers? yes

You can check what the HTML output looks like by clicking on the button. You should see output something like this (but colour-coded):-

<html><head><title>Results</title><body><pre>Name: Simon Huggins
Pay Method: Visa
Offers? yes
</pre></html>

Congratulations! You now have a script where you can both view a form if no data has been sent to the script, otherwise retrieve the data from the form if data has been sent (presumably from the form), and do something with it (display the form data back to the browser in this case). 

Set up web server connection

The next step would be to send the data to your web server.  To do this, you need some basic information about your web server, which you should be able to get from your service provider:-

To specify these to the PerlWiz program so that you can start uploading files to the server, click on the Properties button () on the toolbar, and click on the FTP /Upload heading, and the Server / Login sub-heading.

Type the details detailed above into the appropriate boxes, and (in the Miscellaneous sub-heading) typically also the Upload only files that have changed since the last transfer option too.

You can also check the Keep connection open between transfers option if you are uploading very regularly (e.g. effectively testing on the server itself) and do not wish to wait for the server to connect every time an upload takes place. If the connection is dropped in between uploads, it will be automatically re-established the next time the upload takes place.

To test that the connection works OK, click on the Test Connection button. Make sure you are connected to the Internet before you click on the button.

Results of the test, which consists of logging onto the server, and changing to the start directory, are displayed in the status bar a the bottom of the dialog box. If there were any problems, then the status bar changes to a light-red colour.

Note that these details are stored with the Project. As we are using the default project at the moment, they will be stored automatically - you do not need to type them again once they are set up.

Also note that if you do not wish to save the password of your server for security reasons, you can leave this box blank. You will be prompted for the password each time you need to log onto the FTP server.

Once you are satisfied that the details are correct, click on the Cancel or Close button to exit the dialog box.

Choose program file(s) to upload

Click on the button on the toolbar to try to upload any files that have changed to the web server. As we have not uploaded anything before, the FTP page of the Project Organizer will pop up so that we can select which files we wish to upload.

Click on the name of the file to be uploaded in the list box at the left of the organizer. To specify that the files is to be uploaded to the FTP server, click on the Use this file for uploading to Server checkbox to put a check in it. Notice that the grey arrow next to the name in the list box turns red to show that this is a file that needs uploading. When the file has been uploaded, the arrow turns to green and won't be uploaded again until the file has changed.

We can choose an offset directory if the file is to appear anywhere but the root web server directory (specified previously). E.g. if we had selected /public_html as our root directory for all FTP files, and CGI scripts are kept in /public_html/cgi-bin, then we would select this as cgi-bin

We could change the filename to be stored on the web server here if we wish, but this would be unusual (unless you are uploading a temporary file).

Note that if you hover the cursor over the File Name text box, you will see the full path where the file will be stored on the web server given the current settings. Hovering the cursor over the Offset Destination Directory text box will show the full directory path into which the file will be placed.

We can store a file as ASCII (typical for text, Perl source and HTML files) or Binary (typical for pictures / images), or leave this up to PerlWiz by choosing Auto. We'll leave it as Auto in this case.

The Change File Permissions option sets the file permissions for the file to be uploaded.  This is not available on all web servers, but most Unix servers allow for this. Click on the checkbox, and choose a file permission (typically 755 for Perl scripts). Click on the ellipses (...) button to select the options in more detail using checkboxes for public, group and local permissions. Note that not all servers accept permission changes in this way.

The Project Organizer FTP page should now look something like this:-

Click on the cross to close the window (or press the Esc key on the keyboard). Note that all changes to settings in the Project Organizer update the project immediately. You may wish to save the project at this point using Ctrl+Alt+A.

The file is now set up for uploading. Any changes you make will be detected, and whenever you click on the button in the future, they will uploaded automatically without any further setting up or intervention. This button now acts as a 'Save All' button to your web server for all changed files.

Uploading the program file

Upload the program to the web server now by clicking on the button. If there were any problems, a dialog box will appear showing with a red arrow any files not uploaded. Details of the results of each of the files uploaded (or not) are given in the status bar. Click on any file in the listbox to see details of the last upload for that file (i.e. success or failure) in the status bar.

Testing the program on the server

To specify where the root directory of the web server correlates to on the internet (e.g. http://www.simonhuggins.com might correlate to /public_html on the web server), click on the properties () button on the toolbar, select the Files heading and the File Paths sub-heading, and select the Root URL under the Web Site Details heading as the name of your web site (typically where your home page sits - e.g. http://www.simonhuggins.com). Click on the OK button apply the settings and close the Project Properties dialog box.

To try out the program on the internet (i.e. test where the file has been uploaded to), click on the  button on the toolbar.

This actually does two actions in one - it uploads any changes made to the program (so long as the program has been set up for uploading as described earlier), and then if this completes OK (or is not necessary as the file has not changed), it will launch a browser session using the internet site.

So if you wanted to make any changes to your program, and see the effects immediately on your web site, you only need to click one button - the uploading part is invisible to you.

Server-based test bed - keep in different directories

You may wish to keep two copies of your web site on your server - one that serves as a "live" test area, one that serves as the "live" site itself.

A good idea is to keep a second copy of the site as a subdirectory on the web server (password protected, if you wish) - e.g. under a directory called test.

Then, all you have to do to upload to the test server whilst making changes, is to change the root directory location in the Files >> Backups & Versions heading and the FTP / Upload >> Server / Login heading of the Project Properties dialog box ( button) and add /test onto the end.

Any files will now get saved under this directory.

When you are happy everything is working on the test-bed area of the web site, switch to the live environment by removing the /test off the end of the URL and root directory, and upload everything to the live web site.

Any change to the root upload directory will invalidate any uploads that have been made, making it appear as though all files in the project have changed and need uploading.

Version Control

Once you have started to produce more complex web applications that are changing often, you may wish to keep a history of the changes that you have made.

You could employ the use of a "check-in / check-out" style version-control system - there are plenty on the market, many of them freely available. These are ideal where teams of people are sharing the same code, and you do not wish anyone else to change a program whilst you are working on it.

However, if you only wish to maintain a history so that you can identify what changes were made, when they were made, and how the program has changed between different version or 'releases', then the version control available within PerlWiz will probably be fine.

Each project (including the default project) can have a version control root directory associated to it. This means that any files saved using the project will be stored under a version-specific subdirectory under the version control root directory. Furthermore, any backups will be stored under this subdirectory.

For example, view the project properties tab (click on the button on the toolbar) and click on the Files >> Backups & Versions heading.  You can select the number of backups to keep of any file using the Backups / File options. For example if this was set to 3, then myprog.pl would be moved to myprog.pl.bak when it is changed and saved, and then shuffled into myprog.pl.bak.1 when it is saved again, and then moved to myprog.pl.bak.2 when saved again, and then deleted the next time it is saved, so that myprog.pl.bak always contains the most recent backup. You can restore from these backup using the File | Restore option, which shows the original creation date of each backup file. Note that backups are not stored with a project if you choose to store files inside a project for transporting.

Next, choose a versions path to be the root path - e.g. projects/backups

Next, select the Identification >> About heading in the project properties dialog. This shows the current version number. This is used to create the subdirectory under which all files will be kept.

The directory under which a second copy of the latest source file, plus any backups, is kept is made up of the versions path and the version number, where each dot is converted to a subdirectory, so if the version path is c:\temp\backups and the version number is 1.3, then backups / source copy are kept under c:\temp\backups\1\3. Then, if the version number is changed at any time, when you start working on the next version of the application, all you have to do is change the version number of the project, and any changes are then saved to another directory. Any directories that need to be created are created automatically by PerlWiz.  Note that if you wish to restore from a previous version, you will need to change the version number to the old version first, and then restore the file from the File | Restore menu afterwards, and then change the version number back to the current version number if necessary.

Note that to turn off backups to the versions path, just delete the versions path from the Files >> Backups & Versions heading. Any backups will then be stored in the same directory as the source file. If you do not want to keep any backups, then simply set the Backups / File option to 0 (zero).

You can also prevent a backup being made if the last change was within a certain amount of time - to prevent getting loads of backups if you are saving and testing only minor changes. To use this, set the value in the No backups within ... seconds of last saved backup text box to the number of seconds between backups - e.g. 60 seconds for a minute, or at the extreme, 86400 for a full day between registering backups!

 

(c) Copyright 2003-4 Arctan Computer Ventures Ltd.   All Rights Reserved.
If you have any issues regarding this on-line help, please contact the author by clicking here.
Alternatively, you can leave a voice message on +44(0)7050-618-297 or fax on +44(0)7050-618-298

This Page was last updated: 27 June 2004 06:02