Main Content

Equality and looks like tests - Perl

Archive - Originally posted on "The Horse's Mouth" - 2008-07-29 05:46:30 - Graham Ellis

Whenever you do an equality check in a Perl program, you must think whether you're checking if two numbers are equal, if two test strings are equal, or if a string looks like a pattern. And you write different code in each case:

Checking numbers: If ($stuff == 6) { ...
Tests whether $stuff contains the number 6 (or a string that evaluates to the number 6, or the number 6.0)

Checking text string equality: If ($stuff eq "Well House") { ...
Tests whether $stuff contains exactly the string "Well House"

Checking a text string against a pattern: If ($stuff =~ /hotel/i) { ...
Tests whether the string in $stuff contains, somewhere within it, the word "hotel" in upper case, lower case, or a mixture.

You need to be especially careful not to use the == (numeric) operator to check text strings, as text strings that do not start with digits return zero - so (for example) it would always tell you that two names are the same!

Here's an example to illustrate that:

print "What is your name? ";
chop($hes = <STDIN>);
 
# Numeric equality
 
if ($hes == "Graham") {
   print "Hello and welcome\n";
} else {
   print "Not known\n";
}
 
# String equality - EXACT match!
 
if ($hes eq "Graham") {
   print "Hello and welcome\n";
} else {
   print "Not known\n";
}
 
# String match to regular expression
 
if ($hes =~ /Graham/) {
   print "Hello and welcome\n";
} else {
   print "Not known\n";
}


And some results from testing it:

Dorothy:cs2 grahamellis$ perl u
What is your name? Graham
Hello and welcome
Hello and welcome
Hello and welcome
Dorothy:cs2 grahamellis$ perl u
What is your name? I am Graham Ellis
Hello and welcome
Not known
Hello and welcome
Dorothy:cs2 grahamellis$ perl u
What is your name? Simon Smith
Hello and welcome Test zero against zero
Not known
Not known
Dorothy:cs2 grahamellis$