next up previous contents
Next: Scalar Variables Up: Practical Perl Programming Previous: Example: Back-Quoted Strings

Variables

  In the last chapter, we learned about literals -- values that don't change while your program runs because you represent them in your source code exactly as they should be used. Most of the time, however, you will need to change the values that your program uses. To do this, you need to set aside pieces of computer memory to hold the changeable values. And, you need to keep track of where all these little areas of memory are so you can refer to them while your program runs.

Perl, like all other computer languages, uses variables to keep track of the usage of computer memory. Every time you need to store a new piece of information, you assign it to a variable.

You've already seen how Perl uses numbers, strings, and arrays. Now, you'll see how to use variables to hold this information. Perl has three types of variables:

Scalar
-- denoted by a $ symbol prefix. A scalar variable can be either a number or a string.
Array
-- denoted by a @ symbol prefix. Arrays are indexed by numbers.
Associative Array
-- denoted by a % symbol prefix. Arrays are indexed by strings. You can look up items by name.

Note: This is quite different than Pascal and even C. But Hopefully this makes things easier.

We will deal with arrays in the next chapter. For now we concentrate on scalars

The different beginning characters help you understand how a variable is used when you look at someone else's Perl code. If you see a variable called @Value, you automatically know that it is an array variable.

They also provide a different namespace for each variable type. Namespaces separate one set of names from another. Thus, Perl can keep track of scalar variables in one table of names (or namespace) and array variables in another. This lets you use $name, @name, and %name to refer to different values.

Tip I recommend against using identical variable names for different data types unless you have a very good reason to do so. And, if you do need to use the same name, try using the plural of it for the array variable. For example, use $name for the scalar variable name and @names for the array variable name. This might avoid some confusion about what your code does in the future.

Note Variable names in Perl are case-sensitive. This means that $varname, $VarName, $varName, and $VARNAME all refer to different variables.

Each variable type will be discussed in its own section. You'll see how to name variables, set their values, and some of the uses to which they can be put.



 
next up previous contents
Next: Scalar Variables Up: Practical Perl Programming Previous: Example: Back-Quoted Strings
dave@cs.cf.ac.uk