Perl
  Home arrow Perl arrow Page 3 - Perl Subroutines: Arguments and Values
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 
IBM Developerworks
 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

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

    Table of Contents:
  • Perl Subroutines: Arguments and Values
  • Default Argument Values
  • Scalar Return Values
  • Contextual Return Values

  • 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

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    Perl Subroutines: Arguments and Values - Scalar Return Values
    (Page 3 of 4 )


    Always return scalar in scalar returns.


    One of the more subtle features of Perl subroutines is the way that their call context propagates to their return statements. In most places in Perl, the context (list, scalar, or void) can be deduced at compile time. One place where it can’t be determined in advance is to the right of a return. The argument of areturnis evaluated in whatever context the subroutine itself was called.

    That’s a very handy feature, which makes it easy to factor out or rename specific uses of built-in functions. For example, if you found yourself repeatedly filtering undefined and negative values out of lists:

      @valid_samples = grep {defined($_) && $_ >= 0} @raw_samples;

    it would be better to encapsulate that complex filter and rename it more meaningfully:

      sub valid_samples_in {
         
    return grep {defined($_) && $_ >= 0} @_;
      }

      # and then...

      @valid_samples = valid_samples_in(@raw_samples);

    Because the return expression is always evaluated in the same context as the surrounding call, it’s also still okay to use this subroutine in scalar context:

      if (valid_samples_in(@raw_samples) < $MIN_SAMPLE_COUNT) {
                  
    report_sensor_malfunction();
      }

    When the subroutine is called in scalar context, its return statement imposes scalar context on the grep, which then returns the total number of valid samples—just as a raw grep would do in the same position.

    Unfortunately, it’s easy to forget about the contextual lycanthropy of areturn, especially when you write a subroutine that is “only ever going to be used one way”*. For example:

      sub how_many_defined {
         
    return grep {defined $_} @_;
      }

      # and "always" thereafter:

      my $found = how_many_defined(@raw_samples);

    But eventually someone will write:

      my ($found) = how_many_defined(@raw_samples);

    and introduce a very subtle bug. The parentheses around$foundput it in a list context, which puts the call tohow_many_defined()in a list context, which puts thegrep insidehow_many_defined()in a list context, which causes thereturn to return the list of defined samples, the first of which is then assigned to$found†.

    If there were even the slightest chance that this scalar-returning subroutine might ever be called in a list context, it should have been written as follows:

      sub how_many_defined {
         
    return scalar grep {defined $_} @_;
      }

    There is no shame in using an explicit scalar anywhere you know you want a scalar but you’re not confident of your context. And because you can never be confident of your context in a return statement, an explicit scalar is always acceptable there.

    At very least, you should always add one anywhere that a previously mistaken expectation regarding context has already bitten you. That way, the same misconception won’t bite whoever is eventually responsible for the care and feeding of your code (that is, most likely you again, six months later).

    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