Book HomeLearning Perl, 3rd EditionSearch this book

2.5. Scalar Variables

A variable is a name for a container that holds one or more values.[54] The name of the variable stays the same throughout the program, but the value or values contained in that variable typically change over and over again throughout the execution of the program.

[54]As we'll see, a scalar variable can hold only one value. But other types of variables, such as arrays and hashes, may hold many values.

A scalar variable holds a single scalar value, as you'd expect. Scalar variable names begin with a dollar sign followed by what we'll call a Perl identifier: a letter or underscore, and then possibly more letters, or digits, or underscores. Another way to think of it is that it's made up of alphanumerics and underscores, but can't start with a digit. Uppercase and lowercase letters are distinct: the variable $Fred is a different variable from $fred. And all of the letters, digits, and underscores are significant, so:

$a_very_long_variable_that_ends_in_1

is different from:

$a_very_long_variable_that_ends_in_2

Scalar variables in Perl are always referenced with the leading $. In the shell, you use $ to get the value, but leave the $ off to assign a new value. In awk or C, you leave the $ off entirely. If you bounce back and forth a lot, you'll find yourself typing the wrong things occasionally. This is expected. (Most Perl programmers would recommend that you stop writing shell, awk, and C programs, but that may not work for you.)

2.5.1. Choosing Good Variable Names

You should generally select variable names that mean something regarding the purpose of the variable. For example, $r is probably not very descriptive but $line_length is. A variable used for only two or three lines close together may be called something simple, like $n, but a variable used throughout a program should probably have a more descriptive name.

Similarly, properly placed underscores can make a name easier to read and understand, especially if your maintenance programmer has a different spoken language background than you have. For example, $super_bowl is a better name than $superbowl, since that last one might look like $superb_owl. Does $stopid mean $sto_pid (storing a process-ID of some kind?) or $s_to_pid (converting something to a process-ID?) or $stop_id (the ID for some kind of "stop" object?) or is it just a stopid mispelling?

Most variable names in our Perl programs are all lowercase, like most of the ones we'll see in this book. In a few special cases, capitalization is used. Using all-caps (like $ARGV) generally indicates that there's something special about that variable. (But you can get into an all-out brawl if you choose sides on the $underscores_are_cool versus the $giveMeInitialCaps argument. So be careful.)

Of course, choosing good or poor names makes no difference to Perl. You could name your program's three most-important variables $OOO000OOO, $OO00OO00, and $O0O0O0O0O and Perl wouldn't be bothered -- but in that case, please, don't ask us to maintain your code.

2.5.2. Scalar Assignment

The most common operation on a scalar variable is assignment, which is the way to give a value to a variable. The Perl assignment operator is the equals sign (much like other languages), which takes a variable name on the left side, and gives it the value of the expression on the right. For example:

$fred = 17;            # give $fred the value of 17
$barney = 'hello';     # give $barney the five-character string 'hello'
$barney = $fred + 3;   # give $barney the current value of $fred plus 3 (20)
$barney = $barney * 2; # $barney is now $barney multiplied by 2 (40)

Notice that last line uses the $barney variable twice: once to get its value (on the right side of the equals sign), and once to define where to put the computed expression (on the left side of the equals sign). This is legal, safe, and in fact, rather common. In fact, it's so common that we can write it using a convenient shorthand, as we'll see in the next section.

2.5.3. Binary Assignment Operators

Expressions like $fred = $fred + 5 (where the same variable appears on both sides of an assignment) occur frequently enough that Perl (like C and Java) has a shorthand for the operation of altering a variable -- the binary assignment operator. Nearly all binary operators that compute a value have a corresponding binary assignment form with an appended equals sign. For example, the following two lines are equivalent:

$fred = $fred + 5; # without the binary assignment operator
$fred += 5;        # with the binary assignment operator

These are also equivalent:

$barney = $barney * 3;
$barney *= 3;

In each case, the operator causes the existing value of the variable to be altered in some way, rather than simply overwriting the value with the result of some new expression.

Another common assignment operator is the string concatenate operator ( . ); this gives us an append operator ( .= ):

$str = $str . " "; # append a space to $str
$str .= " ";       # same thing with assignment operator

Nearly all binary operators are valid this way. For example, a raise to the power of operator is written as **=. So, $fred **= 3 means "raise the number in $fred to the third power, placing the result back in $fred".



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.