Perl Variables

It’s time for you to get acquainted with the idea of a variable. Variables are very important in programming. They provide containers that you use to store information for later retrieval and manipulation. You choose a name for your variable (hopefully picking a nice, descriptive name that will make sense to you later on), then stick a value in it (or a bunch of values, or pairs of values; more on that in a minute). Later, you can get that value (values, pairs of values) back by referring to the variable by name. This actually sounds more complicated than it is. The following examples should help clear things up.

There are three types of variables in Perl. In increasing order of niftiness, they are scalar, array, and hash variables. You’ll be using them all, so let’s get to know them.

Scalar Variables

Replace the print statement in your "Hello, world!” script with the following:

$greeting = "What are you looking at?\n";

print $greeting;

This new form of the script uses a variable to hold the string that will be printed. First the string is assigned to the variable using the assignment operator, an equal sign (=). Then we feed the variable (called $greeting) to the print function.

In Perl, variables whose names begin with a dollar sign ($) are used to store a single something: a single number or a single string of text. Programmers call these single-something containers scalar variables.

Tip

When I say scalar variables hold a single string of text, I don’t mean they ...

Get Perl for Web Site Management now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.