Node:Scalar Variables, Next:, Previous:Numbers, Up:Working with Scalars

Scalar Variables

Since we have now learned some useful concepts about strings and numbers in Perl, we can consider how to store them in variables. In Perl, both numeric and string values are stored in scalar variables.

Scalar variables are storage areas that you can use to store any scalar value. As we have already discussed, scalar values are strings or numbers, such as the literals that we discussed in previous sections.

You can always identify scalar variables because they are in the form $NAME, where NAME is any string of alphanumeric characters and underscores starting with a letter, up to 255 characters total. Note that NAME will be case sensitive, thus $xyz is a different variable than $xYz.

Note that the first character in the name of any scalar variable must be $. All variables that begin with $ are always scalar. Keep this in mind as you see various expressions in Perl. You can remember that anything that begins with $ is always scalar.

As we discussed (see A First Perl Program), it is best to always declare variables with the my function. You do not need to do this if you are not using strict, but you should always use strict until you are an experienced Perl programmer.

The first operation we will consider with scalar variables is assignment. Assignment is the way that we give a value from some scalar expression to a scalar variable.

The assignment operator in Perl is =. On the left hand side of the =, we place the scalar variable whose value we wish to change. On the right side of the =, we place the scalar expression. (Note that so far, we have learned about three types of scalar expressions: string literals, numeric literals, and scalar variables).

Consider the following code segment:

     use strict;
     my $stuff = "My data";  # Assigns "My data" to variable $stuff
     $stuff = 3.5e-4;        # $stuff is no longer set to "My data";
                             # it is now 0.00035
     my $things = $stuff;    # $things is now 0.00035, also.

Let us consider this code more closely. The first line does two operations. First, using the my function, it declares the variable $stuff. Then, in the same statement, it assigns the variable $stuff with the scalar expression, "My data".

The next line uses that same variable $stuff. This time, it is replacing the value of "My data" with the numeric value of 0.00035. Note that it does not matter that $stuff once contained string data. We are permitted to change and assign it with a different type of scalar data.

Finally, we declare a new variable $things (again, using the my function), and use assignment to give it the value of the scalar expression $stuff. What does the scalar expression, $stuff evaluate to? Simply, it evaluates to whatever scalar value is held by $stuff. In this case, that value is 0.00035.