Building simplicidade.org: notes, projects, and occasional rants

if unless

In Perl, you can do something like VERB if CONDITION or VERB unless CONDITION.

There is not clear rule about which one to use, and I can say that I've preferred one of the other at different parts of my Perl-life.

Recently, I've settled on a simple rule to decide which one to use. The decision is based on the type of CONDITION that follows.

For me, something like 'CONDITION && CONDITION' is much easier to read and understand than 'CONDITION || CONDITION'. The reason is simple: the first, using &&, has less positive outcomes, and usually thats the one you are testing for, so my brain doesn't need to keep several possible options in my memory. I can short-circuit and forget what was before the && as soon as I decide that it is true.

So my current rule is simple: use the one who converts your condition to a &&.

So if I have:

return unless $estado eq 'clean' || $estado eq 'dirty';

I rewrite it as:

return if $estado ne 'clean' && $estado ne 'dirty';

update: I need sleep, really. Updated the examples to make some sense. Thanks to Pedro Leite.