1. Technology

Comparison Operators - How to compare values in Perl

Comparison Operators - Equal, Not Equal

By

Next: Comparison Operators - Greater Than, Greater Than or Equal To

Perl comparison operators can sometimes be confusing to new Perl programmers. The confusion stems from the fact that Perl actually has two sets of comparison operators - one for comparing numeric values and one for comparing string (ascii) values. Since comparison operators are typically used to control logical program flow and make important decisions, using the wrong operator for the value you are testing can lead to bizarre errors and hours of debugging if you're not careful.

The simplest and probably most used comparison operators test to see if one value is equal to another value. If the values are equal, the test returns true and if the values are not equal, the test returns false. For testing the equality of two numeric values, we use the comparison operator ==. For testing the equality of two string values, we use the comparison operator eq (EQual).

 if (5 == 5) { print "== for numeric values\n"; }
 if ('moe' eq 'moe') { print "eq (EQual) for string values\n"; } 
Testing for the opposite, not equal, is very similar. Remember that this test will return true if the values tested are not equal to each other. To see if two numeric values are not equal to each other, we use the comparison operator !=. To see if two string values are not equal to each other, we use the comparison operator ne (Not Equal).
 if (5 != 6) { print "!= for numeric values\n"; }
 if ('moe' ne 'curly') { print "ne (Not Equal) for string values\n"; } 
Remember that when we talk about string values being equal to each other, we're referring to their ascii values. So the capital letters are technically less than the lowercase letters, and the higher the letter is in the alphabet, the higher the ascii value. Make sure you check your ascii values if you're trying to make logical decisions based on strings.

Next: Comparison Operators - Greater Than, Greater Than or Equal To

  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Comparison Operators - How to compare values in Perl

©2014 About.com. All rights reserved.