The text and programs here are from the first edition of CGI Programming 101. This has been replaced by the 2nd edition; please click here to view the updated material from the 2nd edition.

Chapter 2: Perl Variables

Before you can proceed much further with Perl, you'll need some understanding of variables. A variable is just a place to store a value, so you can refer to it or manipulate it throughout your program. Perl has three types of variables: scalars, arrays, and hashes.

A scalar variable stores a single (scalar) value. Perl scalar names are prefixed with a dollar sign ($), so for example, $x, $y, $z, $username, and $url are all examples of scalar variable names. Here's how variables are used:

You do not need to declare a variable before using it; just drop it into your code. A scalar can hold data of any type, be it a string, a number, or whatnot. You can also drop scalars into double-quoted strings:

Now if you print $blee, you will get "The magic number is 23."

Let's edit first.pl again and add some scalars to it:

Source code: http://www.cgi101.com/class/ch2/first.txt

Save, and run the script in the Unix shell. (This program will not work as a CGI.) This time, the program will prompt you for your name, and read your name using the following line:

STDIN is standard input. This is the default input channel for your script; if you're running your script in the shell, STDIN is whatever you type as the script runs.

The program will print "Hello there. What is your name?", then pause and wait for you to type something in. (Be sure to hit return when you're through typing your name.) Whatever you typed is stored in the scalar variable $you. Since $you also contains the carriage return itself, we use

to remove the carriage return from the end of the string you typed in. The following print statement:

substitutes the value of $you that you entered. The "\n" at the end if the line is the perl syntax for a carriage return.

Arrays

An array stores a list of values. While a scalar variable can only store one value, an array can store many. Perl array names are prefixed with an at-sign (@). Here is an example:

In Perl, array indices start with 0, so to refer to the first element of the array @colors, you use $colors[0]. Note that when you're referring to a single element of an array, you prefix the name with a $ instead of the @. The $-sign again indicates that it's a single (scalar) value; the @-sign means you're talking about the entire array.

If you wanted to loop through an array, printing out all of the values, you could print each element one at a time:

Or, a much easier way to do this is to use the foreach construct:

For each iteration of the foreach loop, Perl sets $i to an element of the @colors array - the first iteration, $i is "red". The braces {} define where the loop begins and end, so for any code appearing between the braces, $i is set to the current loop iterator.

Array Functions

Since an array is an ordered list of elements, there are a number of functions you can use to get data out of (or put data into) the list:

In these examples we've set $elt to the value returned, but you don't have to do that - if you just wanted to get rid of the first value in an array, for example, you'd just shift(@arrayname). Both shift and pop affect the array itself, by removing an element; in the above example, after you pop "yellow" off the end of @colors, the array is then equal to ("red", "green", "blue", "cyan", "magenta", "black"). And after you shift "red" off the front, the array becomes ("green", "blue", "cyan", "magenta", "black").

You can also add data to an array:

@colors now becomes ("green", "blue", "cyan", "magenta", "black", "orange").

@colors now becomes ("green", "blue", "cyan", "magenta", "black", "orange", "purple", "teal","azure").

Here are a few other useful functions for array manipulation:

@colors now becomes ("black", "blue", "cyan", "green", "magenta" ). Note that sort does not change the actual values of the array itself, so if you want to save the sorted array, you have to do something like this:

The same thing is true for the reverse function:

@colors now becomes ("black", "magenta", "cyan", "blue", "green" ). Again, if you want to save the inverted list, you must assign it to another array.

In this example, $#colors is 4. The actual length of the array is 5, but since Perl lists count from 0, the index of the last element is length - 1. If you want the actual length of the array (the number of elements), you'd use the scalar function:

In this case, scalar(@colors) is equal to 5.

@colors becomes a single string: "black, magenta, cyan, blue, green".

Hashes

A hash is a special kind of array - an associative array, or paired group of elements. Perl hash names are prefixed with a percent sign (%), and consist of pairs of elements - a key and a data value. Here's how to define a hash:

Another way to define a hash would be as follows:

The => operator is a synonym for ", ". It also automatically quotes the left side of the argument, so enclosing quotes are not needed.

This hash consists of a person's name for the key, and their URL as the data element. You refer to the individual elements of the hash with a $ sign (just like you did with arrays), like so:

In this case, "fred" is the key, and $pages{'fred'} is the value associated with that key - in this case, it would be "http://www.cgi101.com/~fred/".

If you want to print out all the values in a hash, you'll need a foreach loop, like follows:

This example uses the keys function, which returns an array consisting only of the keys of the named hash. One drawback is that keys %hashname will return the keys in random order - in this example, keys %pages could return ("fred", "beth", "john") or ("beth", "fred", "john") or any combination of the three. If you want to print out the hash in exact order, you have to specify the keys in the foreach loop:

Hashes will be especially useful when you use CGIs that parse form data, because you'll be able to do things like $FORM{'lastname'} to refer to the "lastname" input field of your form.

Let's write a simple CGI using the above hash, to create a page of links:

Source code: http://www.cgi101.com/class/ch2/urllist.txt
Working example: http://www.cgi101.com/class/ch2/urllist.cgi

Call it urllist.cgi, save it, and change the permissions so it's executable. Then call it up in your web browser. You should get a page listing each person's name, hotlinked to their actual URL.

Chapter 3 will expand this concept as we look at environment variables and the GET method of posting forms.

Hash Functions

Here is a quick overview of the Perl functions you can use when working with hashes.

Resources

Visit http://www.cgi101.com/class/ch2/ for source code and links from this chapter.


Copyright © 2000 by Jacqueline D. Hamilton.
Chapter 1 Table of Contents Chapter 3