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$ (written 2008-07-29 05:46:30)
Associated topics are indexed under
P104 - Perl - Conditional CodeP204 - Perl - Conditionals and LoopsP212 - Perl - More on Character Strings
Some other Articles
Apache httpd, MySQL, PHP - installation procedurePunting on the CamBack from the futureA short Perl exampleEquality and looks like tests - PerlHot Courses - PerlA future vision for Melkshamaddslashes v mysql_real_escape_string in PHPBath - Melksham - Devizes. Bus route changes, new timetablePHP examples - source code and try it out too