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


in reply to Re^2: return value of "if" (documentation?)
in thread return value of "if" (documentation?)

You're right; I intended to link to perlsub. I still think that it's applicable, though I would be in full agreement that the documentation ought to be more explicit about it, unless specifying the behavior more explicitly locks future p5p development into a behavior that they would prefer to change.

Update:

I've submitted the following perlbug:
----------------------------------------------------------------- [Please describe your issue here] perlsub says this about implicit returns: If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified. Now consider the following code: $x = 1; sub foo { if( $x ) { 0 } } print foo(), "\n"; The output will be 0, presumably because the last statement is the expression, numeric '0'. How about this: $x = 0; sub foo { if( $x ) { 1 } } print foo(), "\n"; The output will be 0, presumably because the last expression to be evaluated is '$x', which has a value of 0. But the last statement to execute is literally "if()". If we run this past B::Concise we find that the construct is converted into something similar to sub { $x and 1 }, so it is intuitive that the return value will be $x if false, or 1 if $x is true. Although this behavior is possibly a little confusing to someone who doesn't read between the lines in perlsub, it seems reasonably stable (it's been with us forever), and unlikely to change in the future. Therefore, perlsub should state the following: If no L<return> is found and if the last statement is an expression, its value is returned. If the last statement is an C<if( CONDITION ) { BLOCK }> construct, the value of the return value will come from C<BLOCK> if C<CONDITION> is true, or from C<CONDITION> if C<CONDITION> is false. Relying on this behavior is detrimental to code legibility. If the last statement is a loop control structure like a C<foreach> or a C<while>, the returned value is unspecified. [Please do not change anything below this line] ----------------------------------------------------------------- ---

If it gains the consideration of p5p I anticipate they will want to rehash the wording a bit before proceeding, or possibly simply make the if(){} construct explicitly unspecified, as has been done with loop constructs.


Dave