Usage of ‘if’ versus ‘unless’ for Perl conditionals

JSBձոգչ picture JSBձոգչ · Jun 15, 2010 · Viewed 56.4k times · Source

What are some guidelines for the best use of if versus unless in Perl code? Are there strong reasons to prefer one or the other in some situations?

Answer

friedo picture friedo · Jun 15, 2010

In Perl Best Practices, the advice is to never use unless. Personally, I think that's lunacy.

I use unless whenever there's a simple condition that I would otherwise write as if( ! ... ). I find the unless version to be more readable, especially when used as a postfix:

do_something() unless $should_not_do_that;

I recommend avoiding unless anytime things get more complicated, such as when you will have elsif or else blocks. (Fortunately, or perhaps unfortunately, depending on your perspective, there is no elsunless)

Also, any time a conditional is a complex expression made up of other booleans. For example,

unless( $foo and !$bar )

Is pretty damn confusing, and does not have any advantage over the equivalent if.