http://www.perlmonks.org?node_id=1069711


in reply to return value of "if" (documentation?)

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