Home arrow Perl Programming arrow Page 3 - Returns and Perl Subroutines

Implicit Returns - Perl

In this final part of a three part series covering subroutines in Perl, we will discuss returns and return values, as well as prototypes. This article is excerpted from chapter nine of the book Perl Best Practices, written by Damian Conway (O'Reilly; ISBN: 0596001738). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Returns and Perl Subroutines
  2. Prototypes
  3. Implicit Returns
  4. Returning Failure
By: O'Reilly Media
Rating: starstarstarstarstar / 4
August 29, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


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, orundefif 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 behaves—there’s no other word for it—oddly 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:

    if (odd($num)) {

or in:

        return $num if $prev_found;

The last expression is the (failed) conditional test of thewhileloop. Whatwhile loop? The implicitwhileloop that the Perl compiler secretly translates everyforloop 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 explicitreturnstatement—even 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 expecte
d
 
}

  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.



 
 
>>> More Perl Programming Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: