Perl
  Home arrow Perl arrow Page 4 - 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

    PCmover - $15 Off with Coupon Code CJPH7Q

    Returns and Perl Subroutines - Returning Failure
    (Page 4 of 4 )


    Use a bare return to return failure.


    Notice that each final return statement in the examples of the previous guideline used a return keyword with no argument, rather than a more-explicit return undef.

    Normally, relying on default behaviour is not best practice. But in the case of areturnstatement, relying on the default return value actually prevents a particularly nasty bug.

    The problem with returning an explicit return undef is that—contrary to most people’s expectations—a returned undef isn’t always false.

    Consider a simple subroutine like this:

      use Contextual::Return;

      sub guesstimate{
          my ($criterion) = @_;

          my @estimates;
          my $failed = 0;

          # [Acquire data for specified criterion]

          return undef if $failed;

          # [Do guesswork based on the acquired data]

          # Return all guesses in list context or average guess in scalar context...
         
    return (
              LIST { @estimates          }
              SCALAR { sum(@estimates)/@estimates;             }
         
    );
      }

    The successful return values are both fine, and completely appropriate for the two contexts in which the subroutine might be called. But the failure value is a serious problem. Sinceguesstimate()specifically tests for calls in list context, it’s obvious that the subroutine is expected to be called in list contexts:

      if (my @melt_rates = guesstimate('polar melting')) {
          my $model = Std::Climate::Model->new({ polar_melting => \@melt_rates });

          for my $interval (1,2,5,10,50,100,500) {
          print $model->predict({ year => $interval })
          }
      }

    But if the guesstimate() subroutine fails, it returns a single scalar value: undef. And in a list context (such as the assignment to @melt_rates), that single scalar undef value becomes a one-element list: (undef). So @melt_rates is assigned that one-element list and then evaluated in the overall scalar context of the if condition. And in scalar context an array always evaluates to the number of elements in it, in this case 1. Which is true.

    Oops!*

    What should have happened, of course, is thatguesstimate()should have returned a failure value that was false in whatever context it was called, i.e.,undefin scalar context and an empty list in list context:

      if ($failed) {
         
    return (
             
    LIST   { ()    }
             
    SCALAR { undef }
         
    );
      }

    But that’s precisely what areturnitself does when it’s not given an argument: it returns whatever the appropriate false value is for the current call context. So, by always using a barereturnto return a “failure value”, you can ensure that you will never bring about the destruction of the entire planetary ecosystem because of an expectedly trueundef.

    Meanwhile, Chapter 13 presents a deeper discussion on the most appropriate ways to propagate failure from a subroutine.


    * Yep, that’s the sound of alarm bells you’re hearing.

    † And if that sample happens to be an integer, then $found will be assigned a numeric value, exactly as expected. It will be the wrong numeric value, but hey, at least that will make the bug much more interesting to track down.

    * They’d be the “edge-cases”, except that, in this instance, they’re conceptually in the middle of possibilities.

    * And here “Oops!” means: theifblock executes despite the failure ofguesstimate()to acquire any meaningful data. So, when the climate model requests a numerical polar melting rate, thatundefis silently converted to zero. This dwimmery causes the model to show that polar melting rates have absolutely no connection to world climate in general, and to rising ocean levels in particular. So mankind can happily keep burning fossil fuels at an ever-greater rate, secure in the knowledge that it has no effect. Until one day, the only person left is Kevin Costner. On a raft.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 1 hosted by Hostway