in reply to Simplify code in Perl with "unless" condition

unless (...) is the equivalent of if (not (...)) - it only simplifies your code if it makes it more readable. For example, you might find next LINE unless format_is_ok($line); more readable than next LINE if !format_is_ok($line);. When in doubt, stick with if. Also, unless is a conditional statement like if, not a "loop".

Replies are listed 'Best First'.
Re^2: Simplify code in Perl with "unless" loop -- De Morgan's laws
by Discipulus (Canon) on May 28, 2016 at 12:50 UTC
    unless (...) is the equivalent of if (not (...))

    yes this is obviously true, but can be error prone in the case of complex conditions.

    De_Morgan's_laws are useful in this case to do the correct translation between the plain and the negated form of a (possibly comlpex) condition.

    I was suggested to investigate such laws when i had an Untillian Headache

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re^2: Simplify code in Perl with "unless" loop
by Chaoui05 (Scribe) on May 27, 2016 at 15:42 UTC
    Oh yes ! I did a big mistake. INdeed, it's a conditionnal and not a loop..end of week Thanks , i changed it in my post edit
    Lost in translation
      When you update your post: use strike tags and then put in correction. If you change the question mid-stream, posts to the original question are confusing. Make this update explicit.

      And yes "unless" is just the "NOT of if". These are all the "same".

      #!/usr/bin/perl use strict; use warnings; my $x = 5; print "x not 3\n" unless $x==3; print "x not 3\n" if $x!=3; print "x not 3\n" if !($x==3);
      Usually the "if version" is more clear. However in the above, since $x is seldom exactly 3, "unless" focuses on the usual action with Perl's ability to put the "action" first and the conditional last. For longer blocks, most often use some form of "if".
        I will Marshall . Thanks for reply
        Lost in translation