Section 9.11. Implicit Returns


9.11. Implicit Returns

Always return via an explicit return.

If a subroutine "falls off the end" without ever encountering an explicit return, the value of the last expression evaluated in a subroutine is returned. That can lead to completely unexpected return values.

For example, consider this subroutine, which is supposed to return the second odd number in its argument list, or undef if there isn't a second odd number in the list:

     sub find_second_odd {         my $prev_odd_found = 0;         # Check through args...         for my $num (@_) {             # Find an odd number...             if (odd($num)) {                 # Return it if it's not the first (must be the second)...                 return $num if $prev_odd_found;                 # Otherwise, remember it's been seen...                 $prev_odd_found = 1;             }         }         # Otherwise, fail     }

When that subroutine is used, strange things happen:

     if (defined find_second_odd(2..6)) {         # find_second_odd(  ) returns 5         # so the if block does execute as expected     }     if (defined find_second_odd(2..1)) {         # find_second_odd(  ) returns undef         # so the if block is skipped as expected     }     if (defined find_second_odd(2..4)) {         # find_second_odd(  ) returns an empty string (!)         # so the if block is unexpectedly executed     }     if (defined find_second_odd(2..3)) {         # find_second_odd(  ) returns an empty string again (!)         # so the if block is unexpectedly executed again     }

The subroutine works correctly when there is a second odd number to be found, and when there are no numbers at all to be considered, but it behavesthere's no other word for itoddly for the in-between cases[*]. That anomalous empty string is returned because that's what a failed boolean test evaluates to in Perl. And a failed boolean test is the last expression evaluated in the loop. No, not the conditional in:

[*] They'd be the "edge-cases", except that, in this instance, they're conceptually in the middle of the full range of possibilities.

         if (odd($num)) {

or in:

             return $num if $prev_found;

The last expression is the (failed) conditional test of the while loop. What while loop? The implicit while loop that the Perl compiler secretly translates every for loop into.

That's the problem. In order to predict the implicit return value of anything but the simplest subroutine, you not only have to understand the control flow within the subroutine and how that flow may change under different argument lists, but also what sneaky manipulations the compiler is performing on your code before it's executed.

But none of those complications will ever trouble you if you simply ensure that your subroutines can never "fall off the end". And all that requires is that every subroutine finishes with an explicit return statementeven if you have to add one "gratuitously":

      sub find_second_odd {         my $prev_odd_found = 0;         
# Check through args...
for my $num (@_) {
# Find an odd number...
if (odd($num)) {
# Return it if it's not the first (must be the second)...
return $num if $prev_odd_found;
# Otherwise, remember it's been seen...
$prev_odd_found = 1; } }
# Otherwise, fail explicitly
return; }

Now the subroutine always behaves as expected:

      if (defined find_second_odd(2..6)) {         
# find_second_odd(  ) returns 5         # so if the block is executed, as expected
} if (defined find_second_odd(2..1)) {
# find_second_odd(  ) returns undef         # so if the block is skipped, as expected
} if (defined find_second_odd(2..4)) {
# find_second_odd(  ) returns undef         # so if the block is skipped, as expected
} if (defined find_second_odd(2..3)) {
# find_second_odd(  ) returns undef         # so if the block is skipped, as expected
}

That extra return is a very small price to pay for perfect predictability.

Note that this rule applies even if your subroutine "doesn't return anything". For example, if you're writing a subroutine to set a global flag, don't write:

     sub set_terseness {         my ($terseness) = @_;         $default_terseness = $terseness;     }

If the subroutine isn't supposed to return a meaningful value, make it do so explicitly:

      sub set_terseness {         my ($terseness) = @_;         $default_terseness = $terseness;         return;  
# Explicitly return nothing meaningful
}

Otherwise, developers who use the code could misinterpret the lack of an explicit return as indicating a deliberate implicit return instead. So they may come to rely on set_terseness( ) returning the new terseness value. That misinterpretation will become a problem if you later realize that the subroutine actually ought to return the previous terseness value, because that change in behaviour will now break any client code that was previously relying on the "undocumented feature" provided by the implicit return.



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net