Operators in Perl
This time, I will talk about comparison operators, string operators, and arithmetic operators. What are they and what are they used for? Well, that will be the focus of this tutorial. Without further delay, let’s get started.
Comparison Operators
To start, I will talk about comparison operators. These operators are used to compare strings and/or numbers. However, they use different notations, meaning the operator for strings is different from the operator for numbers. It is important to never confuse the operators because you might end up with errors in your program and then waste time searching for the problem.
For example, if we want to compare numbers, we must use mathematical operators such as <
, >
, =
While for strings, we use string-oriented operators such as eq
, ne
, lt
, etc.
Initially, this might seem strange because you might not know their meanings. To help you learn, here is a table showing the meaning of the operators and their equivalents for strings and numbers:
a < b ; #b is greater than a;
a eq b ; # comparing strings requires the usage of eq operator
1 eq "teste"; # invalid comparison
"teste" == "teste"; # invalid comparison
Table of Comparison Operators
Comparison | Numeric | String |
---|---|---|
Equal | == | eq |
Not equal | != | ne |
Less than | < | lt |
Greater than | > | gt |
Less than or equal | <= | le |
Greater than or equal | >= | ge |
Equivalence | <=> | cmp |
Arithmetic Operators
Arithmetic operators, or “mathematical operation signs,” are the same as in math, but their usage in programming languages is slightly different. Since it is not necessary to explain each one in detail here, I leave you a small table with the operators and their functions:
Operator | Function |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
** | Exponentiation |
% | Modulo (remainder) |
Logical Operators
These operators are used to perform boolean operations (1 or 0 / True or False). There are only 3 logical operators, as shown in the table below:
Operator | Alternative Operator | Meaning |
---|---|---|
&& | and | Logical AND |
|| | or | Logical OR |
! | not | Logical NOT |
Example:
1 && 2; # check for true conditional
1 or 2; # check if at least one is true
!2; #negate valeus