The Original Web-Wise-Wizard
Web Authors, Web Developers and Webmasters Internet Toolbox
Best viewed at 1024 x 768 using a colour depth greater than 256

CGI Tutorial - Perl Scripting Examples

This page has been tested and conforms to WCAG 2.0 Accessibility Guidelines
Server-side Programming - CGI Perl

About This Page ...

This page contains a number of unrelated Perl scripting examples, each of which does a different low-level job. The page is intended to act both as a reference and as a tutorial. The examples all work on both the Windows and Linux Platforms and should work on any CGI supporting web server.

Unrelated Examples ...

This page contains Perl scripting examples that were difficult to find when I started learning Perl and I still use the page as a reminder when I am writing Perl programmes. All the examples I have provided work equally well on my Windows NT/Apache web server and on my Linux/Apache web servers.

If you have any similar Perl examples that you feel could be useful to other people who are learning Perl then please E-Mail them to me. If published they could be subject to editing but we will give full credit and if you would like us to do so, we will also provide a link to your site at the bottom of this page. I am expecting this page to grow exponentially and regard it as a service to those struggling to learn Perl programming.

We have created a separate page for Perl regular expressions which enables us to concentrate on Perl scripting examples on this page. Both pages will be developed indepentantly and if you want to view our Perl regular expressions page then you can do so using the following link.

Page Contents ...

 

The Perl Scripts ...

Internal Server Path

Many Perl programs require you to manually enter your web server's internal path as a constant at the beginning of the program. In my experience this can be a real pain, particularly if you want to run the script on several different servers because it means keeping different copies of the script for upload.

I always get the Perl script to ascertain the web server's internal path for itself by using the CGI 'DOCUMENT_ROOT' variable and this method has never failed to work for me.

 

WARNING: Since writing the above script we have found a server that actually returns the wrong information for the CGI 'DOCUMENT_ROOT' variable. We don't know if this is being done intentionally by the operators of the server or if it is a sloppy or mis-configuration. Whatever the case this means that there is at least one server where you will have to obtain the server path information and manually edit the script to reflect the correct server path. It may not be relevant but the problem server uses the FreeBSD operating system whereas all the other servers we have tested this routine on use the Linux or Windows operating system.

Redirect From Inside A Script

It is often very useful to simply serve a different page to the user from inside a script. This snippet requires a path relative to the web servers root directory. Once called the substitute page takes on all the properties of the existing page or CGI script (e.g. filename, relative location, etc.). This directive will not accept a URL (e.g. http://etc.) or a server path to determine the location of the substitute page.

 

You must remember to include the two newlines at the end of the string otherwise you will receive an error and you must also ensure that you have not previously issued a 'Content-type: text/html' directive or you will simply get your 'Location:' string displayed in the browser. Perhaps the major advantage of this method of redirection is that all your SSI directives on the substitute page remain intact and operate quite normally.

Test If A File Exists

There are occasions when I find it extremely useful to test for a file's existence before attempting to open it or do other operations that are dependant upon wether the file exists or not.

check if a file does exist ...

 

check if a file doesn't exist ...

 

Current Working Directory (1)

This routine checks the Perl system variable $0 ($PROGRAM_NAME) to check that there is a valid path preceding the program name. If there is a valid path preceding the program name then it reads the current working directory from system variable $1. If there is no valid path preceding the program name then is sets the current working directory variable to a period (denoting current directory).

 

It is worth noting that the behaviours of the system variables $0 and $1 are inconsistent and can vary from system to system. On some systems the $0 system variable will return the program name only whilst on other systems the $0 system variable will return the full server path to the current program. If the $0 system variable doesn't include a path with the program name then the $1 system variable will have no value.

Current Working Directory (2)

This second current working directory routine appears to be far more reliable than the one above and it has behaved consistently on all the systems that we have checked it on. It does what we hoped the routine above would do and simply returns the correct full server path to the current working directory.

 

NS Lookup IP Number From Domain Name

Here's is a script that looks deceptively simple and works on every platform we have tried it on. You must provide the domain name you wish to lookup (e.g. anydomain.com) and the IP Address of a reliable DNS Server. After calling the script the '$responseDetails' variable should contain details of the DNS server plus information gathered about the Domain name. Alternatively, it may only contain information about the DNS server in which case there is no information available about the Domain name. Another alternative is that it might return some sort of error (e.g. server not found). You have to write your own script to parse the response details and extract the information you require.

 

There are two things to note about this script. The first is that you must have network access to the DNS server you specify (this typically means being connected to the Internet) and the format of the response details is likely to be DNS server specific which means that you must write your parsing script for a specific DNS server's responses.

Numeric Sort/Array Pointers Example

In it's basic usage the Perl sort function will only sort arrays into alphabetical order which means that you have to write your own compare routines if you want to sort arrays numerically. Worse still, is the fact that that the Perl sort routine can only sort single-dimension arrays which leaves you on your own, if for example you want to sort by different elements in multi-dimension arrays or you want to sort objects by property. This script introduces you to the concept of doing your own sorting by showing you how to quicksort an indexed array numerically. An added bonus with this script is that it shows you how to pass and and work on pointers to an array rather than creating and returning a new array each time you do a sort.

initialize an array and call the subroutine ...

 

the numeric sort subroutine ...

 

associated notes ...

You should remember that there are two types of array in Perl. The first type of array is the 'indexed array' which uses the '@ sign' to denote that it is an indexed array (e.g. @array) and then uses numeric subscripts (e.g. $array[0]) to reference elements in the array. The second type of array is the 'associative array' which uses the '% sign' to denote that it is an associative array (e.g. %array) and then uses named subscripts (e.g. $array{'ELEMENT_NAME'}) to reference elements in the array. The above script will only work on indexed arrays and you would require a variation of the script to sort associative arrays numerically or to sort multi-dimension arrays, etc.

Passing pointers to arrays is a highly efficient way of manipulating data in Perl but you should remember that any changes that are made to the array are made directly to the original array and this may not be what you want to do.

Get Day Name/Day Number From Date

The basis of this routine started life with me some 20 years ago when I was learning to write programs in AppleSoft basic and has since been successfully translated into a myriad number of programming languages, including web development languages Perl and JavaScript, and at one stage it was expanded into a full 'C' time/date library. The routine is both compact and accurate, and it really has stood the test of time.

There are several Perl routines around that appear to do the job job of calculating the day of the week that a given date falls on but this is the only routine that I know of that is accurate all the time. Prior to converting this routine to Perl I used three different Perl scripts that I downloaded from the Web or extracted from Perl Modules and they were all inaccurate some of the time. The year 2001 seemed to cause some particular problems.

 

Strip HTML Tags (1)

This method uses Regular expressions.

http://www.rocketaware.com/perl/perlfaq9/How_do_I_remove_HTML_from_a_stri.htm

 

Many folks attempt a simple-minded regular expression approach, like s/<.*?>//g, but that fails in many cases because the tags may continue over line breaks, they may contain quoted angle-brackets, or HTML comment may be present. Plus folks forget to convert entities, like < for example.

 

The most correct way (albeit not the fastest) is to use HTML::Parse from CPAN (part of the libwww-perl distribution, which is a must-have module for all web hackers).

If you want a more complete solution, see the 3-stage striphtml program in
http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz.

 

Link Directly To This Page ...

help support free information on the Internet ...

Many users prefer to link directly to individual content pages on Web-Wise-Wizard. If you would like to do this then we have provided the following HTML/CSS link script which you can copy and paste directly into your HTML editor. Alternatively, you might like to use our New Dynamic Link Generator to create a link that more fully meets your own particular requirements.

the link displayed ...

Web-Wise-Wizard - Perl Scripting Examples Useful Perl programming routines, each of which does a different low-level job. The page is a reference and as a tutorial and all examples work on Windows and Linux or any CGI supporting web server.

select/copy the link Markup ...

Featured Tutorial
Want More Traffic? Increase your Link Popularity and your PageRank by learning how to use Web Directories
Link To Us Scripts
New Dynamic Link Generator
 
If you find this page interesting or useful then others are likely to view it in exactly the same way. Providing a link to the page will be considered by the search engines as casting a vote for the page. In turn, this will help to improve the search engine ranking of the page resulting in more people being able to see the page. Your link really does count so please don't delay.
 
Post your link NOW!
 
 
Perl/Regular Expressions Links
 
 
 
Copyright © 1998,2014, Gilbert Hadley, Liverpool, England