Perl
  Home arrow Perl arrow Page 2 - 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 - 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 uses swap_arrays() , and anyone who subsequently has to maintain that code, has to know about that subroutine’s special magic. Other wise, 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 that clip_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 that clip_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 %range was 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
     

       

    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 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek