Contents | Up | Prev | Next |
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; $x = 2; print $myvar, " * ", $x, " = " , ($myvar*$x), "\n"; $x = 10; print $myvar, " * ", $x, " = " , ($myvar*$x), "\n"; $x = 75; print $myvar, " * ", $x, " = " , ($myvar*$x), "\n"; $x = 24; print $myvar, " * ", $x, " = " , ($myvar*$x), "\n";
The output of this program is:
17 * 2 = 34 17 * 10 = 170 17 * 75 = 1275 17 * 24 = 408
Several things can be noticed:
Contents | Up | Prev | Next |
Written by Shlomi Fish