Cgi scripting With Perl What Is cgi? 4 Why cgi? 4

Дата канвертавання25.04.2016
Памер226.48 Kb.

CGI Scripting with Perl

What Is CGI? 4

Why CGI? 4

What CGI Provides 4

CGI Restrictions 5

Perl Basics 6

The Traditional Hello World Program 6

Variables 6

Arrays 7

Hashes 7

Filehandles 8

Operators 8

Control Structures 11

Subroutines 14

Creating A Simple Perl CGI script 16

Hello World CGI 16

Generating HTML with 17

Getting Data from the User 18

Debugging CGI Scripts 20

HTML Form Elements 21

Text Boxes and Areas 21

Checkboxes and radio buttons 22

Selection Lists 23

Buttons 24

Hidden Fields 24

Using Tables to Layout a Form 25

Hit Counter 26

Returning an Image 26

Creating An Image 27

Keeping A Counter 28

The Final Counter 29

A CGI message board 30

Design Decisions 30

Posting New Messages 31

Displaying Messages 33

Listing Messages 34

Bringing it All Together 37

Accessing Databases with Perl 39

The DBI and DBD Modules 39

Moving The Message Board to a Database 39

Additional Material 45

Quoting Strings in Perl 45

Regular Expressions 47

Using Perl and CGI on my PC 53

Getting and Installing Perl 53

Getting and Installing a Web Server 53

What Is CGI?

CGI stands for Common Gateway Interface. CGI is the method by which a web server can pass information from to an external program from the web browser. More simply, CGI is programming for the web. A CGI can be written in almost any programming language.

Why CGI?

CGI enables you to add interactive content to your web pages.

You can often use Java or Javascript to make a web page interactive; however, they depend on the browser used. A CGI only depends on the server and so will work for all browsers. A CGI executes on the server and thus can access files and databases on the server as well.
You can also use ASP for the same tasks as CGI. ASP is a proprietary product and so will only work on Windows servers. CGI will work with almost all servers on almost all types of machines and thus has more chance of working with what you have now, and what you might change to later.
It should be noted that the windows version of Perl comes with an extension called PerlScript that allows you to write ASP pages (amongst other things) in perl anyway. Of course you use an ASP interface not a CGI interface but the language is the same.

What CGI Provides

CGI provides a way of executing an arbitrary program on the web server. This program can receive data from the web browser and send data back to the web browser.

It is a batch process, however. The CGI script receives data from the web browser and then sends some data back. It can’t send some data and then wait for a reply. In effect the browser sends all its data and then waits for the CGI script to send its data.
A CGI script can send almost anything to the browser, from a web page to an mpeg movie. The most common data is of course HTML, which the browser will render for the user to see.

CGI Restrictions

CGI has some restrictions that relate to the way the HTTP protocol works. The main problem is that CGI is stateless; there is no such thing as a session.

Each request for a page is separate from every other request; there is no perfect way of knowing if there is one user or ten users at the site at once.
For our purposes this won't matter, since we aren't doing anything that requires state. The obvious example of something that does is a shopping cart web site. Cookies are the usual solution, though if you don’t need persistent state (by which we mean, that if the user leaves the web site and comes back next week the shopping cart will be just as it was when they left) you can also use techniques such as URL encoding.

Perl Basics

Perl is a very large language. I have been using it for seven years and I still don’t use all of the available features.

In this short course, we will not be looking at anywhere near all of Perl, we will just look at the small subset that we will need in order to write some CGI applications.
For simplicity, this section will not deal with CGI; we will be looking at perl programs that you can execute directly in a DOS window.
If you are serious about learning perl then you really should invest in a good book about the language. Computer textbooks are expensive and good ones are hard to find. My advice is to avoid anything with a phrase like "in 10 days" or "for dummies" in the title. Anything with "CGI" in the title is best avoided as well, as most are terrible.
Elements of Programming with Perl by Andrew Johnson and Learning Perl on Win32 Systems by Schwartz, Olson and Christiansen are good choices.

The Traditional Hello World Program

Traditionally the first program written in any new language is a hello world program. Here is hello world in perl:

print "Hello World\n";
That's it. Short and sweet, and easy to understand. Though it shows using a perl function (print), using a string ("Hello World\n"), using a special character (\n), and separating statements (;).


A fundamental concept in programming is that of variables. A variable is simply just a named place to keep data. Because it has a name you know where to look to get the data back later.

Here's the hello world program modified a little to use a variable:
$hello = "Hello World\n";

print $hello;

The $ sign in front of the variable tells perl that it is a scalar variable. A scalar variable is a variable that holds a single value. The actual value can be a string (as we have above) or a number amongst other things.


There are also variables that hold more than one value. Perl has two types of these, arrays and hashes.

An array is an ordered list of scalars. You can access any element in an array by its position. Arrays in Perl are zero-based, this means that the first element has index 0. Here's an example of an array:
@animals = ("cat", "dog", "rat");

print $animals[1];

$animals[3] = "horse";
Notice that arrays are prefixed with a @. Also when accessing a single element of an array we use $ instead of @. That is because the single element is a scalar.
There are a lot of functions that manipulate arrays. The perl documentation is a good place to find information about them all.


A Hash is an unordered list of scalars. You can access any element in the hash by its key. In some ways a hash is like an array that is indexed by strings instead of by numbers. Here's an example:
%day = ( "Sun" => "Sunday",

"Mon" => "Monday",

"Tue" => "Tuesday",

"Wed" => "Wednesday",

"Thu" => "Thursday",

"Fri" => "Friday",

"Sat" => "Saturday",


print $day{"Tue"},"\n";

Notice that hashes are prefixed with a %. And again when we access an individual element of the hash we prefix with a $, since the element is a scalar.
Also note that we can print more than one thing at once.


Filehandles are used to read and write files. You create a file handle with the open function. open takes two parameters, the filehandle and the filename. Usually a filehandle will be used for just reading, or just writing, it is possible to open a file for both reading and writing though.

Here's an example using filehandles:
open(INFILE,"input") or die "Open error:$!";

open(OUTFILE,">output") or die "Open error:$!";

while () {

print OUTFILE $_;

The above will read in the file called input and copy it to a file called output.


Perl provides a large number of operators; some work with numbers others with strings.

Arithmetic Operators

Arithmetic operators are just like the ones you used back in school:



$a + $b


$a * $b


$a - $b


$a / $b


$a % $b

modulus (like remainder)

$a ** $b


Precedence is just like in school, and you can use parenthesis to get a different order.

String Operators

There are only a couple of string operators.

Concatenation is done with the dot operator. This is different from the + operator for addition because Perl doesn't distinguish between strings and numbers as much as other languages.
For example:
$foo = 12;

$bar = 34;

print $foo + $bar, "\n"; #prints 46

print $foo . $bar, "\n"; #prints 1234

There is also a repeat operator for strings: x. Here is an example:
$foo = 12;

$bar = 3;

print $foo x $bar; #prints 121212
String concatenation is not used that often in perl programs. That's because perl interpolates variables into strings. This means if you include a variable in a string perl will replace the variable with its value. For example:
$foo = "Hello";

$bar = "Goodbye";

print "$foo and $bar\n";

Logical Operators

Logical operators deal with whether something is true or false. Perl has two ways of specifying each of its logical operators, the C way, and the very low precedence English way.



$a && $b

and, true of both $a and $b are true

$a || $b

or, true if one or both of $a and $b are true

! $a

not, true if $a is false and vice-versa

$a and $b


$a or $b


not $a


What constitutes true and false in perl is important when dealing with the logical operators. A scalar is false if it is the number 0, or the empty string "", or the string "0", or the undefined value. A scalar is true if it is not false.

Logical operators short-circuit. What this means is if you do something like: $a || print "fred" perl will output fred if $a has a false value only. If $a if true then there is no need to evaluate the print, since the result of the operation is known. This technique is used a lot in perl, especially when opening files.

Comparison Operators

Comparison operators allow us to see how two scalar values relate. Perl has both numeric and string comparison operators

Numeric Example

String Example


$a == $b

$a eq $b


$a != $b`

$a ne $b


$a < $b

$a lt $b

Less than

$a > $b

$a gt $b

Greater than

$a <= $b

$a le $b

Less than, or equal to

$a >= $b

$a ge $b

Greater than, or equal to

$a <=> $b

$a cmp $b

0 if equal, 1 if $a>$b, -1 if $b>$a

Shortcuts Assignment Operators

Perl provides shortcut assignment operators for many common tasks. Some examples are the best way to show these:

$a+=$b; #same as $a = $a + $b

$a/=$b; #same as $a = $a / $b

$a||=$b #same as $a = $a || $b – good for defaults

Increment and Decrement

Perl also provides increment and decrement operators. They are an easy way to add or subtract one from a variable as in:

$a++; #same as $a = $a + 1

$a--; #same as $a = $a – 1

The increment operator can also be applied to strings. In which case it gives the next string in a dictionary order sequence.
$string = "hello";

$string++; #string now equals "hellp"

$string = "zzzz";

$string++; #string now equals "aaaaa"

This can be very useful for membership codes and other values which need to assigned in a sequence, but are not numbers.

Control Structures

Control structures allow us to write programs that respond to their inputs, instead of just doing the same thing every time.

If and unless

if and unless enable us to write code that will only get executed if a certain condition is true or false. For example:

print "Enter your age\n";

$age = ;

if ($age < 27)


print "You are younger than me\n";


unless ($age == 27)


print "You are not my age\n";

You can also use else with if and unless as so:
unless ($condition)


print "$condition is false\n";




print "$condition is true\n";

If you have a lot of cases then elsif might help:
if ($age < 27)


print "You are younger than me\n";


elsif ($age > 27)


print "You are older than me\n";




print "You are the same age as me\n";

In case you are wondering there is no elsunless.

Looping Constructs

It is often useful to perform the same operation multiple times. Loops provide a way to have the same section of code executed a number of times.

While and until

The while and until loops are similar to the if and unless selection statements. Instead of executing the code once if the condition is true (or false for until), they keep executing it until the condition is false (or true for until).

Here is a simple example that counts to ten:
$count = 1;

while ($count <= 10)


print "Count: $count\n";




The foreach statement is used to execute a block of code for each of a set of scalars. Here's an example of counting to ten again:
foreach $count (1 ... 10)


print "Count: $count\n";



The for statement works in a similar fashion to the while statement. It looks more complicated, and is not used very often in perl programs. The foreach statement is used instead most of the time.

Here is an example of counting to ten again:
for($count=1 ; $count <= 10 ; $count++)


print "Count: $count\n";

The for statement is made up of four sections.
The initialise. $count=0 above. This is executed once at the start of the loop.
The test. $count <= 10 above. If this is true then the body of the loop will be executed.
The body. The print section above. This is executed is the test is true.
The increment. $count++ above. This is executed after the body, then the test is checked again and the process continues until the test is finally false when the loop terminates.
To confuse matters a bit, you can also write a foreach loop using the word for. For example the following is valid perl code (and is useful for those too lazy to type each):
for $count (1 ... 10)


print "Count: $count\n";


next and last

Next and last are used to change the flow of a loop. They are very useful for

dealing with special cases.
The next statement causes the loop to start the next iteration. It is used to skip over some of the data. For example we could write a loop to print out all of the values in an array that are greater than 10 as so:
foreach $value (@array)


if ($value <= 10)




print "$value\n";

The last statement is used to terminate a loop completely. It is useful if you are looping through an array searching for an element, there is after all no point continuing once you have found it. Here is an example that sets a variable to be true if there is a value greater than 10 in an array:
$found = 0;

foreach $value (@array)


if ($value > 10)


$found = 1;





Subroutines allow us to write a piece of code once and have it be called from many different places. This is a good thing, as means that when we later want to change the code we only need change it in one place.

Here is an example of a subroutine, which concatenates its arguments, placing a comma in between each of them.
sub concat


my $result = "";

foreach (@_)


$result .= "$_,";


chop $result;

return $result;

print concat(1,2,3,4,5),"\n";

print concat("one","two","three"),"\n";
There is a lot in the example so lets look at it one bit at a time.
sub concat defines a subroutine called concat, the code following it is the code that will be executed when the subroutine is called.
my is a keyword in perl that declares a new variable. The variable will disappear when the current scope (technical term, basically the set of enclosing braces) ends.
@_ is a special array. Any arguments passed to the subroutine are put in the @_ array, so the foreach loop in the example will loop once for each argument.
The foreach loop doesn't specify a variable. If this is done then perl uses $_ as the variable. In fact $_ is used by a lot of things in perl as the default variable.
chop is a function provided by perl. It removes the last character of a scalar. We are using it to remove the trailing "," which will be on the end of the string.
Finally return is used to return a value from a subroutine.


Comments are parts of the code that are for the reader of code and not for the computer. The computer ignores comments so you can put whatever you like in them.

Comments are useful in a number of different ways: explaining what some code does to the reader of the code, explaining what a variable is used for or what units the data in it is in, making notes to yourself, commenting out code that isn't working as you expect to try and find out why, etc.
In perl comments begin with a # and continue until the end of the line, as shown in the following example:
# This is a comment

$name = ; #get the users name from the keyboard

#$name = "sam";

print $name,"\n";


Perl has the concept of a context. Every operation perl performs is done in a context. There are three contexts : scalar, list, and void.

Assigning to a scalar creates a scalar context, assigning to an array creates a list context, void contexts occur when you are ignoring the result of an operation.
There are a few perl functions, which return different results depending on the context they are invoked in. This is something to watch out for if a function is not behaving as you expect it to.
Also an array in a scalar context is converted into the number of elements in the list. This is useful as it can be used to get the length of an array, and can be used as a test to see if an array has any elements.

Creating A Simple Perl CGI script

A CGI script is just like any other perl program. In order for it to work however, it must comply with the CGI specification. Even a simple hello world type CGI script must follow the rules.

A CGI script must output a header before it outputs the data it wants to send to the web browser. The header tells the browser what type of data is about to be sent.

Hello World CGI

Here is a hello world CGI script:

#!C:\Perl\bin\perl.exe -wT

print "Content-type: text/html\n\n";

print "Hello";

print "

Hello World

База данных защищена авторским правом © 2016
звярнуцца да адміністрацыі

    Галоўная старонка