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

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

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

    Returns and Perl Subroutines - Prototypes
    (Page 2 of 4 )

     


    Don’t use subroutine prototypes.


    Subroutine prototypes allow you to make use of more sophisticated argument-passing mechanisms than Perl’s “usual list-of-aliases” behaviour. For example:

      sub swap_arrays (\@\@){
          my ($array1_ref, $array2_ref) = @_;

          my @temp_array = @{$array1_ref};
         
    @{$array1_ref} = @{$array2_ref};
         
    @{$array2_ref} = @temp_array;

          return;
      }

      # and later...

      swap_arrays(@sheep, @goats);      # Implicitly pass references

    The problem is that anyone who usesswap_arrays(), and anyone who subsequently has to maintain that code, has to know about that subroutine’s special magic. Otherwise, they will quite naturally assume that the two arrays will be flattened into a single list and slurped up by the subroutine’s@_, because that’s what happens in just about every other subroutine they ever use.

    Using prototypes makes it impossible to deduce the argument-passing behaviour of a subroutine call simply by looking at the call. They also make it impossible to deduce the context in which particular arguments are evaluated. A subtle but common mistake is to “improve” the robustness of an existing library by putting prototype specifiers on all the subroutines. So a subroutine that used to be defined:

      use List::Util qw( min max );

      sub clip_to_range {
          my ($min, $max, @data) = @_;

          return map { max( $min, min($max, $_) ) } @data;
      }

    is updated to:

      sub clip_to_range($$@) { # takes two scalars and an array
         
    my ($min, $max, @data) = @_;

          return map { max($min, min($max, $_)) } @data;
      }

    The problem is thatclip_to_range()was being used with an elegant table-lookup scheme:

      my %range = (
          normalized => [-0.5,0.5],
         
    greyscale  => [0,255],
         
    percentage => [0,100],
         
    weighted   => [0,1],
     
    );

      # and later...

      my $range_ref = $range{$curr_range};
      @samples = clip_to_range( @{$range_ref}, @samples);

    The $range{$curr_range} hash look-up returns a reference to a two-element array corresponding to the range that’s currently selected. That array reference is then dereferenced by putting a @{ ... } around it. Previously, when clip_to_range() was an ordinary subroutine, that dereferenced array found itself in the list context, so it flattened into a list, producing the required minimum and maximum values for the
    subroutine’s first two arguments.

    But now thatclip_to_range()has a prototype, things go very wrong. The prototype starts with a$, which looks like it’s telling Perl that the first argument must be a scalar. But that’s not what prototypes do at all.

    What that$prototype does is tell Perl that the first argument must be evaluated in a scalar context. And what is the first argument? It’s the array produced by@{$range{$curr_range}}. And what do you get when an array is evaluated in a scalar context? The size of the array, which is 2, no matter which entry in%rangewas actually selected.

    The second argument specification in the prototype is also a $. So the second argument to clip_to_range() must also be evaluated in a scalar context. And that second argument? It’s @samples. Evaluating that array in scalar context once again produces its size. The second argument becomes the number of samples.

    The final specification in the prototype is a@, which specifies that any remaining arguments are evaluated in list context. Of course, there aren’t any more arguments now, but the@specifier doesn’t complain about that. An empty list is still a list, as far as it’s concerned.

    Adding a prototype didn’t really improve the robustness of the code very much. Before it was imposed,clip_to_range()would have been passed the selected minimum, followed by the selected maximum, followed by all the data samples. Now, thanks to the wonders of prototyping,clip_to_range()always gets a minimum of 2, followed by a maximum equal to the number of samples, followed by no data. And Perl doesn’t complain at all, since the prototype was successfully matched by the given arguments, even though it hosed them in the process.

    Prototypes cause far more trouble than they avert. Even when they are properly understood and used correctly, they create code that doesn’t behave the way it looks like it ought to, which makes it harder to maintain code that uses them. Furthermore, in OO implementations they engender a completely false sense of security, because they’re utterly ignored in any method call.

    Don’t use prototypes. The only real advantage they can confer is allowing array and hash arguments to effectively be passed by reference:

      swap_arrays(@sheep, @goats);

    But even then, if you need pass-by-reference semantics, it’s far better to make that explicit:

      sub swap_arrays {
          my ($array1_ref, $array2_ref) = @_;

          my @temp_array = @{$array1_ref};
         
    @{$array1_ref} = @{$array2_ref};
         
    @{$array2_ref} = @temp_array;

          return;
      }

      # and later...

      swap_arrays(\@sheep, \@goats);     # Explicitly pass references

    Note that the body of swap_arrays() shown here is exactly the same as in the prototyped version at the start of this guideline. Only the call syntax varies. With prototypes it’s magical, and therefore misleading; without prototypes it’s a little uglier, but shows at a glance exactly what the code is doing.

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