Perl Operators: Part 2
Numeric ComparisonThese operators are used to compare two numbers, but not to compare strings. We'll get to those next. These operators are typically used in some type of conditional statement that executes a block of code or initiates a loop. We'll get to the conditional statements in the next section, but to introduce this we will use the beginning of an if () condition. Before that, let's look at the list:
|!=||Not Equal to|
|>=||Greater than or Equal to|
|<=||Less than or Equal to|
So, suppose you want to execute some code only if one number is equal to another. You would use the if () condition with the == operator above:
Since money is equal to 5, it would execute the code you place between the curly brackets. It works the same way if you use one of the other operators:
This time it would not go through, as 5 is not less than 3-- the value of $money.
String ComparisonThese are similar to the numerical comparisons, but they work with strings. We will note a few differences in the way these work after the list below:
|ne||Not Equal to|
|ge||Greater than or Equal to|
|le||Less than or Equal to|
Strings are equal if they are exactly the same. So, "cool" and "cool" are equal, but "cool" and "coolz" are not. Here is a string equality example:
if ($i_am eq "cool")
....more cool code....
The greater-than and less-than operators compare strings using alphabetical order. Here is a sample:
if ($i_am lt "cool")
print "You are not very cool, dude.";
Logical OperatorsThese are often used when you need to check more than one condition. Here they are:
So, if you want to see if a number is less than or equal to 10, and also greater than zero:
if (($number <= 10) && ($number > 0))
Notice the nested parentheses. Since we are checking for two conditions, we want to be sure the comparison is done first. Thus, they have their own sets of parentheses within the parentheses for the if () condition. Afterward, it checks to see if both conditions are true. Again, more on the conditionals in the next section.
Well, that's it for the operators for now. In the next section, we'll pick up with conditional statements. Let's go on to Conditional Statements.