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:
$
symbol prefix. A scalar variable
can be either a number or a string.
@
symbol prefix. Arrays are indexed
by numbers.
%
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.