Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

  (email not shown publicly)
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Thursday December 22, 2005
02:24 PM

Go ahead, laugh

[ #28098 ]

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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • 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.
    # I had a sig when sigs were cool
    use Sig;
  • 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 ;-)
    • "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?

      • 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 p
  • 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.