Introduction to Operators

Let's get acquainted with Perl operators in this lesson.

What are operators?

An operator is something that takes one or more values (or expressions) and yields another value, so that the construction itself becomes an expression. For instance, when you add two numbers, 2 and 5, it yields 7. The expression looks like 2+5=7.

Types of operators

There are multiple types of operators for various purposes, such as:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Assignment operators

The following figure illustrates the various kinds of operators in Perl:

Arithmetic operators

Arithmetic operators, as the name suggests, are used for performing basic arithmetic operations. They are further divided into types:

  • Binary Operators
  • Unary Operators

Binary operators

Binary operators are the ones that take two values and perform an arithmetic operation on them.

Here, the operand can be the name of a variable, or it can be a constant like 2, 3, or any other constant.

The following table discusses the various arithmetic operators and their functions.

Operator Function Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
** Exponent $a ** $b

The modulus operator (%) returns the remainder when $a is divided by $b. For example, “5 % 2” will be “1”.

Run the code below to see how these arithmetic operators work in Perl.

Press + to interact
$a = 10;
$b = 4;
print "\$a + \$b = ". ($a + $b); #addition
print "\n";
print "\$a - \$b = ".($a - $b); #subtraction
print "\n";
print "\$a * \$b) = ". ($a * $b); #multiplication
print "\n";
print "\$a / \$b = ". ($a / $b); #division
print "\n";
print "\$a % \$b = ".($a % $b); #modulus returns the remainder of the $a / $b
print "\n";
print "\$a ** \$b = ".($a ** $b); #Exponent (10^4) = 10 * 10 * 10 * 10

In the print statements above, . is used to append the result of expressions with statements in double quotes.

Unary operators

Unary operators are the type of arithmetic operators that perform arithmetic on only one value.

Two commonly used unary operators are discussed below:

  • Incrementing operator: ++
  • Decrementing operator: --

Variables can be incremented by “1” using the ++ operator and can be decremented by “1” using the operator --. They can either precede or succeed variables, resulting in different executions of the code. An example of this is shown below:

Press + to interact
$i = 1;
print $i."\n"; # Prints 1
# Pre-increment operator increments $i by one before using its new value
print ++$i."\n"; # Prints 2
# Pre-decrement operator decrements $i by one before using its new value
print --$i."\n"; # Prints 1
# Post-increment operator uses the current value of the
# variable and then increments
print $i++."\n"; # Prints 1 (but $i value is now 2)
# Post-decrement operator uses the current value of
# the variable and then decrements
print $i--."\n"; # Prints 2 (but $i value is now 1)