A First Script: Hello World
This exercise introduces Perl syntax and basic CGI concepts.
"Hello World" is often the first script a programmer learns in any new
language. The following script will print the words "Hello World" to the
screen of the Web browser when accessed through the appropriate URL.
Open a text editor to write the script (if you are more comfortable using
a different text editor you can change this command):
pico helloworld.cgi
Pico is a simple, display-oriented text editor based on the Pine message
system composer. Type the following Perl code in your text editor
exactly as it appears here:
#!/usr/local/bin/perl [this must
be the first line, or your script won't run]
# simple Hello World script
print "Content-type: text/plain\n\n";
print 'Hello World!';
Save the file and exit the editor by typing ctrl-x. When prompted
"Save modified buffer (ANSWERING "No" WILL DESTROY CHANGES) ?"
type Y. When prompted "File Name to write: helloworld.cgi"
press enter/return.
Make the script executable, type:
chmod 755 $HOME/public_html/cgi-bin/helloworld.cgi
The table below explains helloworld.cgi:
| #!/usr/local/bin/perl |
Tells the server the Perl interpreter is located in
the directory /usr/local/bin/perl. |
| # simple Hello World script |
Is a comment.
Perl comments begin with the # character. Comments are notes
to human readers of the script and are ignored by the Perl interpreter. |
| print "Content-type: text/plain\n\n"; |
Is a print statement. It tells the server to print
the string
enclosed in quotation marks to the Web browser. Double
quotes are used when including variables
or special characters,
like the "\n" in this example. The semicolon indicates the
end of the print statement.
"Content-type: text/plain" is an example of an HTTP
header. This tells the browser to display plain text.
"\n" is how Perl indicates a newline character. Two newline
characters create a blank line, which separates the HTTP header
from the rest of the page. |
| print 'Hello World!'; |
Is the print statement for the body of the page.
Single quotes
are used here since there are no special characters or variables. |
|