2.6. Scalar Operators and Functions
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 equal sign (much like C or FORTRAN), which takes a variable name on the left side and gives it the value of the expression on the right, like so:
$a = 17; # give $a the value of 17 $b = $a + 3; # give $b the current value of $a plus 3 (20) $b = $b * 2; # give $b the value of $b multiplied by 2 (40)
Notice that last line uses the $b variable twice: once to get its value (on the right side of the =), and once to define where to put the computed expression (on the left side of the =). This is legal, safe, and in fact, rather common. In fact, it's so common that we'll see in a minute that we can write this using a convenient shorthand.
You may have noticed that scalar variables are always specified with the leading $. In shell programming, you use $ to get the value, but leave the $ off to assign a new value. In Java 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. (Our solution was to stop writing shell, awk, and C programs, but that may not work for you.)
A scalar assignment may be used as a value as well as an operation, as in C. In other words, $a=3 has a value, just as $a+3 has a value. The value is the value assigned, so the value of $a=3 is 3. Although this may seem odd at first glance, using an ...
Get Learning Perl, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.