Go ahead, laugh

Ovid on 2005-12-22T19:24:17

Yeah, some people think I'm silly for writing conditionals like this:

if (3 eq $my_var) { ... }

But it really saves my butt when I, again, write this:

if (3 = $my_var) { ... }

Particularly on days when my morning coffee doesn't seem to kick in.


Right on

n1vux on 2005-12-22T20:32:13

I agree with you, people think it's strange to write if (3 == $var) and if ('const' eq $var) but it really helps catch errors of the
while ($var=3) { #stealth forever
}

variety. It's like "use strict" for conditions.

use warnings

itub on 2005-12-22T21:05:04

This problem is already caught by "use warnings" or the -w switch:

$ perl -we '$a = 0; if ($a = 1) {print "a == 1!\n" }'
Found = in conditional, should be == at -e line 1.
a == 1!


Granted, it's not normally a fatal error like the one you get by reversing the if, but in my opinion it is enough, and you don't need to resort to the reversal that many people find less readable. (Also, I haven't made that particular mistake in years--I do other kinds of mistakes ;-)

Re:use warnings

tirwhan on 2005-12-23T07:21:48

"use warnings" will however not catch the other scenario, which n1vux mentions, when you have

while ($a = 3) { }

turn into an infinite loop. Nor will it catch

if ($a = my_sub()) { }

(and good thing too). Having said that, I'm puzzled, what is considered to be strange about this formatting? The parentheses around the condition?

Re:use warnings

itub on 2005-12-23T13:55:48

It does warn in the first case:
$ perl -we '$a=0; while($a=3){}'
Found = in conditional, should be == at -e line 1.


But not in the second, so good catch!

"what is considered to be strange about this formatting?"

I'm sure you can get used to it after using it for a while, but there are some of us who like to read from left to right, and place the important things at the beginning of the "sentence" (this may depend on your native language, of course). I see this as a question about $a, not about 3, so I'd rather place the emphasis on $a.

Any good instructor will tell you...

miner on 2006-01-31T21:56:55

That is the only way to construct a conditional.

It forces you to think carefully about times where you actually do want assignment in a conditional (which you may), and it turns erroneous assignments in to a compilation error.

jon