Xref:Perl/c strcmp()

From CoderGuide

Jump to: navigation, search


Performing string comparisons in perl similar to C's strcmp

You compare strings using special operators that can be easy to confuse with the <, >, ==, comparison operators. They are:

eqstrings are equal
nestrings are not equal
ltstring is less than
gtstring is greater than
lestring is less than or equal
gestring is greater than or equal
cmp behaves like c's strcmp(), returns 0 if a match, 1 if greater, -1 if less than.
#!/usr/bin/perl
 
print "strings are equal\n" if ( "string" eq "string");
print "a is greater than b\n" if ( "a" gt "b");
print "a is less than b\n" if ( "a" le "b");
 
## Notice those aren't numerical comparisons? 
## Let's see what happens when we use numerical comparison operators...
 
print "string==string equal\n" if ( "string" == "string");
print "a > b\n" if ( "a" > "b");
print "a < b\n" if ( "a"< "b");
print "a == b\n" if ( "a" == "b");

Output:

strings are equal
a is less than b
string==string equal
a == b

As you can clearly see, Perl's numerical comparators and string comparators do not mix.

Personal tools