Table of Contents

All Equality is Not Equal: Numeric versus String

There are two types of comparison operator; numeric and string. You've already seen two, == and eq. Run this:


if ($foo < $bar) { 
        print "$foo is less than $bar (numeric)\n"; 

if ($foo lt $bar) { 
        print "$foo is less than $bar (string)\n"; 

The lt operator compares in a string context, and of course < compares in a numeric context.

Alphabetically, that is in a string context, 291 comes before 30. It is actually decided by the ASCII value, but alphabetically is close enough. Change the numbers around a little. Notice how Perl doesn't care whether it uses a string comparison operator on a numeric value, or vice versa. This is typical of Perl's flexibility.

Bondage and discipline are pretty much alien concepts to Perl (and the author). This flexibility does have a drawback. If you're on a programming precipice, threatening suicide by jumping off, Perl won't talk you out of your decision but will provide several ways of jumping, stepping or falling to your doom while silently watching your early conclusion. So be careful.