Perl/CGI Scripting Exercise 1

Basic Syntax

 

  1. The first line in every Perl script should be the shebang statement. This gives the location of the Perl interpreter. To find out the location of your Perl interpreter, go to a command prompt and type which perl.

 


Figure 8.1

 

  1. This will give you the location of your Perl interpreter. At the top of every Perl script, the first line (the shebang statement) should read

 

 

  1. Now for our first script, we will simply print out Hello World to the screen and display it in a browser. Create a file in the /var/www/cgi-bin/ directory called test.cgi and insert the following:

 

 

  1. Note that your shebang line will be different if your perl interpreter is located in a different directory.
  2. Change the permissions on the file by going to a command prompt and type

 

 

  1. Now open your web browser and go to http://localhost/cgi-bin/test.cgi
  2. To add comments to a perl script, use the # symbol. For example:

 

 

  1. Variables in perl always begin with a dollar sign ($), at sign (@) or percent sign (%) depending on whether it's a scalar, array, or hash respectively.
  2. A scalar is a character string or a number. It's a good idea to enclose string constants in quotation marks.

10.An array is a list of elements (either character strings, numbers, or both). It is similar to arrays in other programming languages.

11.A hash is a set of scalar pairs. For example:

 

 

12. When printing out variables using the print function, remember to encapsulate everything in double quotation marks. Single quotation marks prints the contents to the screen exactly as they appear. Take a look at the following example (print_test.cgi):

 

 

13.Remember to change the permissions (chmod 755) on all new files you create. They will not work if you don't!

14. You can find text versions of test.cgi and print_test.cgi by clicking here.

 

 

On Your Own Exercise 1

 

Create a .cgi file that displays information about yourself, including name, age, and favorite color.  Declare variables called $name, $age, & $color to store your information.  Print out the values of the variables to the screen.  You MUST comment your code to receive full credit!