Avoid Yoda conditions in Perl you should

Mark Gardner
CodeX
Published in
2 min readDec 28, 2021

--

Paul VanDerWerf from Brunswick, Maine, USA, CC BY 2.0, via Wikimedia Commons

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;

--

--