$x = 3;
$y = "Ovid";
if ($x = $y) {
print "This is true\n";
} else {
print "This is false\n";
}
This code will always print "This is true" because the "=" assigns the value of $y to $x (in this case, both wind up with the value of "Ovid"). The if statement winds up evaluating the true/false value of "Ovid" and concludes because it is not undef and not zero, it must be true and the statement prints. Therefore, the above code probably doesn't behave the way you want it to.
Interestingly, the following snippet will work the way you expect it, but not for the reasons that are immediately obvious:
$x = 3;
$y = 0;
if ($x = $y) {
print "This is true\n";
} else {
print "This is false\n";
}
This code will print "This is false", but not because $x failed to equal $y. In this case, $y is assigned to $x and the if statement evaluated the resulting value, in this case '0' (zero) and zero evaluates as false.
Always remember when using an if statement or other conditional that you usually want to test equality with a logical operator such as "==" for numerics and "eq" for non-numerics. |