4. Variables

Variables are named cells stored in the computer memory that can hold any single Perl value. One can change the value that a variable holds, and one can later retrieve the last value assigned as many times as wanted.

Variables in Perl start with a dollar sign ($) and proceed with any number of letters, digits and underscores (_) as long as the first letter after the dollar is a letter or underscore.

To retrieve the value of a variable one simply places the variable name (again including the dollar sign) inside an expression.

To assign value to a variable, one places the full variable name (including the dollar sign) in front of an equal sign (=) and places the value to the right of the equal sign. This form is considered a statement and should be followed by a semicolon. The value assigned may be an expression that may contain other variables (including the assigned variable itself!).

An example will illustrate it:

$myvar = 17;
$a = 2;
print $myvar, " * ", $a, " = " , ($myvar*$a), "\n";
$a = 10;
print $myvar, " * ", $a, " = " , ($myvar*$a), "\n";
$a = 75;
print $myvar, " * ", $a, " = " , ($myvar*$a), "\n";
$a = 24;
print $myvar, " * ", $a, " = " , ($myvar*$a), "\n";

The output of this program is:

17 * 2 = 34
17 * 10 = 170
17 * 75 = 1275
17 * 24 = 408

Several things can be noticed:

  1. The value of $a changes throughout the program. It's perfectly fine, and usually even necessary to modify the value of a variable.
  2. By using $myvar we can ensure, that assuming we wish to change its value, we will only have to change it in one place, not in every place it appears.

Written by Shlomi Fish