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.
if (3 == $var)
and if ('const' eq $var)
but it really helps catch errors of thewhile ($var=3) { #stealth forever
}
$ perl -we '$a = 0; if ($a = 1) {print "a == 1!\n" }'
Found = in conditional, should be == at -e line 1.
a == 1!
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.
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