Lesson 3 - Operators

An operator is an instruction which yields a new value (a result) from one or more other values (known as operands).

Two operators we have already met are chop() and the assignment operator '=', which assigns the value on its right to the variable on its left, e.g.:

$units = 3.4;   # the variable $units gets set to the value 3.4

The value to the right of the = operator can also be an expression, which is evaluated before the result is assigned to the variable on the left of the =.

$units = $units + 10;    # evaluate the expression ($units + 10), then assign the result to $units

Perl has an abundance of operators, which can be split into several groups according to their function. This lesson introduces Arithmetic Operators, String Operators, Binary Assignment Operators, and Autoincremenet/Autodecrement Operators.

Additional Perl operators are introduced as pertinent to other topics. For example, Comparison Operators are covered as part of Lesson 4 (Control Structures).

3.1 Arithmetic Operators

Perl provides the common arithmetic operators (aka number operators) that you will already be familiar with:

  • + addition
  • - subtraction
  • * multiplication
  • / division

$total = $total + 22;              # Add 22 to the scalar variable $total
$daily_average = $total / 7;   # divide $total by 7, and assign the result to $daily_average

Note that in the second example above, the value of the variable $total does not change. In order for it to change, it would have to be on the left hand side of the assignment operator (=).

There are two further mathematical operators:

  • ** exponentation (raises a value to the nth power)
  • %  modulus (returns the remainder of one operand divided by another)

$cubed = 6**3;             # $cubed gets set to 6 to the power of 3
$remaining = 100 % 30  # remaining gets set to remainder of 100 divided by 30

3.2 String Operators

Perl provides the . operator (a single period) to add strings together. This process is known as concatenation. For example:

$name = 'John Smith';
$greeting = 'Welcome to the home page of ' . $name;
print $greeting;

The output from this code snippet would be:

Welcome to the home page of John Smith

The stings to be concatenated may be string literals or string variables, and more than two may be concatenated in one operation:

print 'Welcome, ' . "$name" . "\n" . 'Please select a menu option' . "\n";

would print:

Welcome,  John Smith
Please Select a Menu Option

Remember from Lesson 2 that $name must be in double quotes - not single - to be interpolated, and that "\n" is the backslash control character for a newline.

Note that in the example above the variable $name is not modified - the concatenation is performed for the purpose of the print operation only.

A second string operator is known as the string repetition operator, denoted by a single lowercase x. This operator takes a string as its left operand, and makes the number of concatenated copies specified by the right operand (a number). e.g.:

'123' x 3         # produces 123123123
"\n" x 8           # produces 8 newline characters

Note that string concatenation does not have to be explicitly invoked via the dot (.) operator - it can also occur implicitly, as with print statements:

print "$z is equal to $x plus $y";

Here $z, $x and $y are being concatenated into the print string (i.e. the output from the print command) behind the scenes, using variable interpolation.

Check Point

$cost = 100;
$tax = $cost * 0.25;
print $cost;
What is printed by the above code fragment?
What is the symbol for the exponentiation ('power of') operator?
Expressions may occur on either side of the = operator: True   False
$pounds = 75;
$conversion_rate = "1.65";
$dollars = $pounds * $conversion_rate;

The above code fragment will give an error, because $conversion_rate is a string,
not a number: True   False


print "*" x 3 . 'EOF' . "*" x 3;
What is printed by the above code fragment?

What is the symbol for the modulus ('remainder') operator?
3.3 Binary Assignment Operators

If you have written programs in other languages, you will be aware that expressions like the following occur frequently:

$total = $total + 10; # Add 10 to $total

The same variable occurs on both sides of the = operator, and Perl has a shorthand notation for this operation of altering a variable - the binary assignment operator. Perl provides a range of these operators, which consists of a number or string operator followed by the = operator. For example, the following two lines are equivalent:

$sum = $sum + 3; # Add 3 to the value of $sum
$sum += 3;           # Add 3 to the value of $sum

Similarly for subtraction, multiplication, and division::

$sum -= 3;  # Subtract 3 form the value of $sum
$sum *= 3; # Multiply $sum by 3
$sum /= 3;  # Divide $sum by 3

What these operations have in common is that the existing value of the operator is altered in some way, rather than being replaced by the result of some new expression.

Binary assignment operators are also provided for string operations, e.g.:

$greeting .= ' ***';   # same as $greeting = $greeting + ' ***'

All of the binary operators are valid in this way - e.g. the modulus operator %= and the 'power of' operator **=.

3.4 Autoincrement and Autodecrement Operators

Perl provides an even shorter notation for adding 1 to a variable than saying $sum += 1. The autoincrement operator ++ adds one to its operand, and returns the incremented value:

++$sum; # Increment $sum by one. (autoincrement used here in prefix form)
$sum++; # Increment $sum by one. (autoincrement used here in suffix form)

Why the two different forms? This becomes apparent when the operator is used on the right hand side of an assignment. For example:

$x = 99;
$y = ++$x; # Both $x and $y are now 100

$x = 99;
$y = $x++; # $y is now 99, but $x is 100

In the first example (prefix form) the value of $x is incremented before it is assigned to $y. In the second example (suffix form) the value of $x is incremented after the initial value of $x is assigned to $y.

Note that the operand for a ++ operator must be a scalar variable rather than an expression, because the value of the operand is changed by the ++. For example, it is not valid to say:

($x + $y)++; # Wrong !

The autodecrement operator -- works in exactly the same way as ++. For example,

$x--; # Decrement $x (by one).
$y = --$x; # Decrement $x then assign the result to $y.

Check Point

What is the binary assignment operator for multiplication?


$x = 5; $y = 10;
$y /= $x;

After execution of this code fragment, what is the value of $y?
After execution of this code fragment, what is the value of $x?
$The += operator can be used in concatenation of strings: True   False
$bonus = 20;
$total = $bonus--;

If the 2nd line here is replaced with $total = --$bonus:
there would be no difference in the final value of $total or $bonus: True   False

Exercises

1. Write a program which inputs an invoice value, then prints out the VAT (Value Added Tax) due on the invoice (hint - store a VAT value, e.g. 17.5%, in a scalar variable).

2. Write a program which prompts the user to enter their age, then prints out the candles they can expect on their next birthday cake as a string (use 'i' to represent a candle). Hint - consider the 'x' string operator.

«previous page
next page»