Home arrow Perl Programming arrow Page 2 - Returns and Perl Subroutines

Prototypes - Perl

In this final part of a three part series covering subroutines in Perl, we will discuss returns and return values, as well as prototypes. This article is excerpted from chapter nine of the book Perl Best Practices, written by Damian Conway (O'Reilly; ISBN: 0596001738). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Returns and Perl Subroutines
  2. Prototypes
  3. Implicit Returns
  4. Returning Failure
By: O'Reilly Media
Rating: starstarstarstarstar / 4
August 29, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 


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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: