Let us now look at how we write our first perl program that will be used as a CGI script.
We will learn three main things in here:
Every Perl program MUST obey the following format:
#!/usr/local/bin/perl
Strictly speaking the first line is only required for running Perl programs on UNIX machines. Since that is the intended destination of most of our Perl scripts. It is a good idea to make this the first line of every perl program. What is the purpose of this first line?
The first line declaration has two purposes:
The first line is actually a comment (albeit a very special type of comment) Comments in Perl
It is good practice to comment all your programs (whatever the language (HTML, Perl, Pascal C) -- Comments serve you well.
In Perl comments are easy:
#
symbol indicates a comment.
#
symbol until
you type a carriage return.
So a simple comment in Perl might be:
# hello.cgi - My first CGI program
Output from Perl
To output from a Perl script you use the print statement:
"... "
)
argument which it outputs.
\n
character indicates that a newline is required
at that point in the text.
\n
characters:
print "Content-Type: text/html\n\n";Finally -- Our complete script
Recall that our Perl CGI script must output the header and HTML code and must begin with a special first line.
Our complete first program (with nice comments) is a follows:
#!/usr/local/bin/perl # hello.cgi - My first CGI program print "Content-Type: text/html\n\n"; # Note there is a newline between # this header and Data # Simple HTML code follows print "<html> <head>\n"; print "<title>Hello, world!</title>"; print "</head>\n"; print "<body>\n"; print "<h1>Hello, world!</h1>\n"; print "</body> </html>\n";