in reply to a question on style
Two comments:
- Leave off the else if you don't use it. Including unused code is usually begging for confusion later on.
- Are you sure your code above is correct? You have an assignment operator "=" instead of a logical operator like "==" or "eq".
Consider the following code:
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.$x = 3; $y = "Ovid"; if ($x = $y) { print "This is true\n"; } else { print "This is false\n"; }
Interestingly, the following snippet will work the way you expect it, but not for the reasons that are immediately obvious:
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.$x = 3; $y = 0; if ($x = $y) { print "This is true\n"; } else { print "This is false\n"; }
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: RE: a question on style
by jrsmith (Pilgrim) on Jun 12, 2000 at 20:36 UTC | |
by Ovid (Cardinal) on Jun 12, 2000 at 20:43 UTC | |
by jcwren (Prior) on Jun 12, 2000 at 20:52 UTC | |
by jrsmith (Pilgrim) on Jun 12, 2000 at 21:35 UTC |
In Section
Seekers of Perl Wisdom