1. Home
  2. Computing & Technology
  3. Perl

Comparison Operators - How to compare values in Perl

Comparison Operators - Less Than, Less Than or Equal To

By Kirk Brown, About.com

There are a variety of comparison operators you can use to determine the logical flow of your Perl programs. We've already discussed the difference between the Perl numeric comparison operators and the Perl string comparison operators, which can cause some confusion to new Perl programmers. We've also learned how to tell if two values are equal to, or not equal to each other, and we've learned how to tell if two values are greater than or equal to each other.

Let's look at the less than comparison operators. Using this first operator, you can test to see if one value is less than another value. To see if two numeric values are less than each other, we use the comparison operator <. To see if two string values are less than each other, we use the comparison operator lt (Less Than).

if (4 < 5) { print "< for numeric values\n"; }
if ('A' lt 'B') { print "lt (Less Than) for string values\n"; }
You can also test for, less than or equal to, which looks very similar. Remember that this test will return true if the values tested are equal to each other, or if the value on the left is less than the value on the right. To see if two numeric values are less than or equal to each other, we use the comparison operator <=. To see if two string values are less than or equal to each other, we use the comparison operator le (Less-than Equal-to).
if (5 <= 5) { print "<= for numeric values\n"; }
if ('A' le 'B') { print "le (Less-than Equal-to) for string values\n"; }
Remember that when we talk about string values being less than 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.

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

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Comparison Operators - How to compare values in Perl

©2008 About.com, a part of The New York Times Company.

All rights reserved.