We recently looked at the basics of Perl and saw how a very simple script could be used to extract information from a file on a web server URL.
We showed how saving a file in Csv format from Excel and writing a few lines of script would make it accessible from any web browser and support basic queries.
The results were displayed as text, which may not be enough if you want to create a good-looking site.
This month, we’ll look at some more functions in Perl and show you how to use pattern matching and substitution to create a script that does much the same job, but uses an HTML file as a template to create attractive results.
Making a template
The first step is to design the page for your results. Some web design tools,
such as Dreamweaver, have methods of creating templates for database-driven
websites, but here we just want something simple.
Using whatever method you fancy, mock up a page designed to show someone’s name, mobile and home phone numbers as in my test script (see attached pdf). You can add extra information if you wish.
We’ll use pattern matching to replace information in the template with data from our Excel Csv file. Start by picking as examples some data that should fit – for example, the longest name in the database – and create a page that looks good.
Try to ensure there’s a clearly defined area of the page where the information will appear and that your design would look good if the contact details were copied and repeated immediately below where they appear. This is so that things still look good when you have more than one result.
Ideally, you want a page that has information above and below the results, such as the company logo, links to other parts of the site and so on.
Next, you need to turn the page into a template that our Perl script can work with. Replace the dummy data with something that doesn’t appear anywhere else in the page. For example, the sequence --NAME-- probably won’t be found elsewhere, and similarly --HOME-- and
--MOBILE-- can be used for the home and mobile phone numbers. We’ll put code in the script to replace these tokens with the genuine data.
How does the script know which is the part of the page it can repeat if there are multiple entries that match our search term? We’ll add a bit of code that marks the start and end of the area where the contact details for each person appear. Do this using HTML comments, so there’s nothing visible on the page. If the editor you use doesn’t have an option to insert comments, switch to viewing the source and enter a line that says
<!-- TEMPLATE BEGIN -->
above the start of the contact area, and below it, add one that says
<!-- TEMPLATE END -->
Take care to avoid breaking any tags, or causing problems with nested tags, if the area is repeated.
All Online Tags: Web Development
