Perl
  Home arrow Perl arrow Page 3 - Returns and Perl Subroutines
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PERL

Returns and Perl Subroutines
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2007-08-29


    Table of Contents:
  • Returns and Perl Subroutines
  • Prototypes
  • Implicit Returns
  • Returning Failure

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Returns and Perl Subroutines - Implicit Returns
    ( Page 3 of 4 )


    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 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 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 sub routine 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 statement—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 Articles          >>> More By O'Reilly Media
     

       

    PERL ARTICLES

    - More Perl Bits
    - Perl, Bit by Bit
    - Basic Charting with Perl
    - Using Getopt::Long: More Command Line Option...
    - Command Line Options in Perl: Using Getopt::...
    - Web Access with LWP
    - More Templating Tools for Perl
    - Site Layout with Perl Templating Tools
    - Build a Perl RSS Aggregator with Templating ...
    - Looping, Security, and Templating Tools
    - Perl: Bon Voyage Lists and Hashes
    - Templating Tools
    - Perl: Number Crunching
    - Perl Debuggers in Detail
    - Debugging Perl





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek