4

Avoid Yoda Conditions in Perl You Should

 2 years ago
source link: https://dzone.com/articles/avoid-yoda-conditions-in-perl-you-should
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Avoid Yoda Conditions in Perl You Should

Assign not when mean to compare you do. Help you warnings and strictures can. Read more in this article about how to avoid "Yoda conditions" in Perl.

Dec. 28, 21 · Open Source Zone · Code Snippet

Join the DZone community and get the full member experience.

Join For Free

I remember a brief time in the mid-2000s insisting on so-called “Yoda conditions” in my Perl. I would place constants to the left of equality comparisons. In case I accidentally typed a single = instead of ==, the compiler would catch it instead of blithely assigning a variable. For example:

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

And, because a foolish consistency is the hobgoblin of little minds, I would even extend this to string and relational comparisons.

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

It looks weird, and it turns out it’s unnecessary as long as you precede your code with use warnings;. Perl will then warn you: “Found = in conditional, should be ==“. (Sidenote: Perl v5.36, due in mid-2022, is slated to enable warnings by default if you do use v5.35; or above, in addition to the strictness that was enabled with use v5.11;. Yay for less boilerplate!)

If you want to fatally catch this and many other warnings, use the strictures module from CPAN in your code like this:

use strictures 2;

This will cause your code to throw an exception if it commits many categories of mistakes. If you’re running in a version control system’s working directory (specifically Git, Subversion, Mercurial, or Bazaar), the module also prevents you from using indirect object syntax, and bareword filehandles.

Getting back to assignments vs. conditionals, there is one case where I’ve found it to be acceptable to use an assignment inside an "if" statement.  That’s when I need to use the result of a check inside the condition. 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 pollute the outer scope with a temporary variable. Fortunately, Perl doesn’t warn on this syntax.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK