    Next: The Logical Operators Up: Operators Previous: The Binary Arithmetic Operators

# The Unary Arithmetic Operators

In common with C, Perl has two short hand unary operators that can prove useful.

The unary arithmetic operators act on a single operand. They are used to change the sign of a value, to increment a value, or to decrement a value. Incrementing a value means to add one to its value. Decrementing a value means to subtract one from its value.

In many statements we frequently write something like:

`\$a = \$a + 1;`

we can write this more compactly as:

`\$a += 1;`.

This works for any operator so this is equivalent:

```\$a = \$a * \$b;
\$a *= \$b;
```

You can also automatically increment and decrement variables in Perl with the ++ and `--` operators.

For example all three expressions below achieve the same result:

```\$a = \$a + 1;
\$a += 1;
++\$a;
```

The ++ and `--` operators can be used in prefix and postfix mode in expressions. There is a difference in their use.

In Prefix the operator comes before the variable and this indicates that the value of the operation be used in the expression: I.e.

```\$a = 3;
\$b = ++\$a;
```

results in a being incremented to 4 before this new value is assigned to b. That is to say BOTH a and b have the value 4 after these statements have been executed.

In postfix the operator comes after the variable and this indicates that the value of the variable before the operation be used in the expression and then the variable is incremented or decremented: I.e.

```\$a = 3;
\$b = \$a++;
```

results in the value of a (3) being assigned to b and then a gets incremented to 4 That is to that after these statements have been executed b = 3 and a = 4.

The Perl programming language has many ways of achieving the same objective. You will become a more efficient programmer if you decide on one approach to incrementing/decrementing and use it consistently.    Next: The Logical Operators Up: Operators Previous: The Binary Arithmetic Operators
dave@cs.cf.ac.uk