Re-read the documentation in perlsub (Link updated; thanks ikegami.) and you will see two big red flags. First:

If no return is found and if the last statement is an expression, its value is returned.

In this construct: my $val = do { if(0){1} };, the last statement evaluated is the conditional, which is numeric zero, so $val gets 0. Had the conditional been true, the last expression evaluated would be the last one in the if statement's block (1, in this case). So unless you explicitly specify an "else" condition, your last expression will be the conditional from the if() statement, if that condition proves false.

The next red flag:

If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified.

So now if your conditional looks like this: my $val = do { if( 1 ) { for( 0 ) { $_ } } };, all bets are off; the behavior is unspecified: You might get a '0' (the last expression), or not... or your keyboard may burst into flames, though Perl isn't prone to doing that under most circumstances. ;)

do{}; blocks can be thought of as immediate-execution subroutines, with implicit(-only) return values.

This tricky behavior is the reason for the recommended ban on "Implicit Returns" in Perl Best Practices (page 197).


Dave


In reply to Re: return value of "if" (documentation?) by davido
in thread return value of "if" (documentation?) by Anonymous Monk

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.