Perl
  Home arrow Perl arrow Page 3 - Returns and Perl Subroutines
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
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? 
PERL

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

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

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Dell PowerEdge Servers

    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, 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 Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Perl Best Practices," published by...
     

    Buy this book now. This article is excerpted from chapter nine of the book Perl Best Practices, written by Damian Conway (O'Reilly; ISBN: 0596001738). Check it out today at your favorite bookstore. Buy this book now.

       

    PERL ARTICLES

    - Perl: A Continuing Look at Hashes and Multid...
    - Perl: Another Round with Hashes
    - Perl Hashes
    - Perl Lists: A Final Look at List::Util
    - Perl Lists: Utilizing List::Util
    - Perl Lists: The Split() Function
    - SQL and CGI with Perl and DBI
    - Perl Lists: More Functions and Operators
    - SELECT Queries and Perl
    - Perl Lists: More on Manipulation
    - Creating a Database with Perl and DBI
    - Perl: Sailing the List(less) Seas
    - Perl and DBI
    - Perl: Concatenating Text and More
    - Perl Text: Quoting Without Quote Marks

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway