This is because of the return value of a subroutine in the absence of a return statement; it is the value of the last statement. In this case, both if and unless have truth values of whatever their argument is if they fail. If they succeed, their truth value is the last statement inside their block. That is:

sub b{unless (!pop) {"unless"} } sub c{if (pop) {"if" } } print "failed if (0): ",c(0), "\n"; print "failed unless (0): ",b(0), "\n"; print "succeeded if (42): ",c(42),"\n"; print "succeeded unless (42): ",b(42),"\n";

prints:

failed if (0): 0 failed unless (0): 1 succeeded if (42): if succeeded unless (42): unless

In this context, it makes sense -- when the conditional is not met, it falls though, and a() returns the last value in the subroutine -- in the "if" case, the value of $c, which is 0. In the case of the unless, it returns the value of !$c, which is 1.

Update: Added two more cases to the example to make it clearer.

perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'


In reply to Re: isn't unless ! $c the same than if $c ? by Chmrr
in thread isn't unless ! $c the same than if $c ? by Anarion

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.