Home > Articles > Web Development > Perl

Scalar Data and Operators in Perl

  • Print
  • + Share This
Laura Lemay and Richard Colburn discuss almost everything you could ever want to know about scalar data. Learn about tables of operators, operator precedence, pattern matching with digits, input and output, and calling functions with and without parentheses around their arguments.
This chapter is from the book

Scalar data, as you learned yesterday, involves individual items such as numbers and strings. Yesterday, you learned several things you could do with scalar data; today, we'll finish up the discussion, show you more operators you can play with, and finish up with some related topics. The things you can expect to learn today are

  • Various assignment operators

  • String concatenation and repetition

  • Operator precedence

  • Pattern matching for digits

  • A short overview of input and output

Assignment Operators

Yesterday, we discussed the basic assignment operator, =, which assigns a value to a variable. One common use of assignment is an operation to change the value of a variable based on the current value of that variable, such as:

$inc = $inc + 100;

This does exactly what you'd expect; it gets the value of $inc, adds 100 to it, and then stores the result back into $inc. This sort of operation is so common that there is a shorthand assignment operator to do just that. The variable reference goes on the left side, and the amount to change it on the right, like this:

$inc += 100;

Perl supports shorthand assignments for each of the arithmetic operators, for string operators I haven't described yet, and even for && and ||. Table 3.1 shows a few of the shorthand assignment operators. Basically, just about any operator that has two operands has a shorthand assignment version, where the general rule is that

variable operator= expression

is equivalent to

variable = variable operator expression

There's only one difference between the two: in the longhand version, the variable reference is evaluated twice, whereas in the shorthand it's only evaluated once. Most of the time, this won't affect the outcome of the expression, just keep it in mind if you start getting results you don't expect.

Table 3.1 Some Common Assignment Operators



Longhand equivalent


$x += 10

$x = $x + 10


$x -= 10

$x = $x - 10


$x *= 10

$x = $x * 10


$x /= 10

$x = $x / 10


$x %= 10

$x = $x % 10


$x **= 10

$x = $x**10

Note that the pattern matching operator, =~, is not an assignment operator and does not belong in this group. Despite the presence of the equals sign (=) in the operator, pattern matching and variable assignment are entirely different things.

  • + Share This
  • 🔖 Save To Your Account