I remem­ber a brief time in the mid-​2000s insist­ing on so-​called Yoda con­di­tions” in my Perl. I would place con­stants to the left of equal­i­ty com­par­isons. In case I acci­den­tal­ly typed a sin­gle = instead of ==, the com­pil­er would catch it instead of blithe­ly assign­ing a vari­able. E.g.:

if ( $foo == 42 ) { ... } # don’t do this
if ( 42 == $foo ) { ... } # do this
if ( $foo = 42  ) { ... } # to prevent this

And because a fool­ish con­sis­ten­cy is the hob­gob­lin of lit­tle minds, I would even extend this to string and rela­tion­al comparisons.

if ( 'bar' eq $foo ) { ... } # weirdo
if ( 42 > $foo )     { ... } # make it stop

It looks weird, and it turns out it’s unnec­es­sary as long as you pre­cede your code with use warnings;. Perl will then warn you: Found = in conditional, should be ==“. (Sidenote: Perl v5.36, due in mid-​2022, is slat­ed to enable warn­ings by default if you do use v5.35; or above, in addi­tion to the strict­ness that was enabled with use v5.11;. Yay for less boilerplate!)

If you want to fatal­ly catch this and many oth­er warn­ings, use the stric­tures mod­ule from CPAN in your code like this:

use strictures 2;

This will cause your code to throw an excep­tion if it com­mits many cat­e­gories of mis­takes. If you’re run­ning in a ver­sion con­trol sys­tem’s work­ing direc­to­ry (specif­i­cal­ly Git, Subversion, Mercurial, or Bazaar), the mod­ule also pre­vents you from using indi­rect object syn­tax, Perl 4‑style mul­ti­di­men­sion­al arrays, and bare­word file­han­dles.

Getting back to assign­ments vs. con­di­tion­als, there is one case where I’ve found it to be accept­able to use an assign­ment inside an if state­ment, and that’s when I need to use the result of a check inside the con­di­tion. For example:

if ( my $foo = some_truthy_function() ) {
    ... # do something further with $foo
}

This keeps the scope of some_truthy_function()s result inside the block so that I don’t pol­lute the out­er scope with a tem­po­rary vari­able. Fortunately, Perl does­n’t warn on this syntax.

5 thoughts on “Avoid Yoda conditions in Perl you should

Comments are closed.