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

Subroutines in Perl
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2007-08-16

    Table of Contents:
  • Subroutines in Perl
  • Homonyms
  • Argument Lists
  • Named Arguments

  • 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

    Dell PowerEdge Servers

    Subroutines in Perl - Named Arguments
    (Page 4 of 4 )


    Use a hash of named arguments for any subroutine that has more than three parameters.


    Better still, use named arguments for any subroutine that is ever likely to have more than three parameters.

    Named arguments replace the need to remember an ordering (which humans are comparatively poor at) with the need to remember names (which humans are relatively good at). Names are especially advantageous when a subroutine has many optional arguments—such as flags or configuration switches—only a few of which may be needed for any particular invocation.

    Named arguments should always be passed to a subroutine inside a single hash, like so:

      sub padded {
          my ($arg_ref) = @_;

          my $gap   = $arg_ref->{cols} - length $arg_ref->{text};
         
    my $left  = $arg_ref->{centered} ? int($gap/2) : 0;
         
    my $right = $gap - $left;

          return $arg_ref->{filler} x $left
                
    . $arg_ref->{text}
                
    . $arg_ref->{filler} x $right;
      }

      # and then...
     
    for my $line (@lines) {
         
    $line = padded({ text=>$line, cols=>20, centered=>1, filler=>$SPACE });
      }

    As tempting as it may be, don’t pass them as a list of raw name/value pairs:

      sub padded {
          my %arg = @_;

          my $gap   = $arg{cols} - length $arg{text};
         
    my $left  = $arg{centered} ? int($gap/2) : 0;
         
    my $right = $gap - $left;

          return $arg{filler} x $left
                
    . $arg{text}
                
    . $arg{filler} x $right;
      }

      # and then...
     
    for my $line (@lines) {
         
    $line = padded( text=>$line, cols=>20, centered=>1, filler=>$SPACE );
      }

    Requiring the named arguments to be specified inside a hash ensures that any mismatch, such as:

      $line = padded({text=>$line, cols=>20..21, centered=>1, filler=>$SPACE});

    will be reported (usually at compile time) in the caller’s context:

      Odd number of elements in anonymous hash at demo.pl line 42

    Passing those arguments as raw pairs:

      $line = padded(text=>$line, cols=>20..21, centered=>1, filler=>$SPACE);

    would cause the exception to be thrown at run time, and from the line inside the subroutine where the odd number of arguments were unpacked and assigned to a hash:

      Odd number of elements in hash assignment at Text/Manip.pm line 1876

    It is okay to mix positional and named arguments, if there are always one or two main arguments to the subroutine (e.g., the string thatpadded()is supposed to pad) and the remaining arguments are merely configuration options of some kind. In any case, when there are both positional arguments and named options, the unnamed positionals should come first, followed by a single reference to a hash containing the named options. For example:

      sub padded {
          my ($text, $arg_ref) = @_;

          my $gap   = $arg_ref->{cols} - length $text;
         
    my $left  = $arg_ref->{centered} ? int($gap/2) : 0;
         
    my $right = $gap - $left;

          return $arg_ref->{filler} x $left . $text . $arg_ref->{filler} x $right;
      }

      # and then...
     
    for my $line (@lines) {
         
    $line = padded( $line, {cols=>20, centered=>1, filler=>$SPACE} );
      }

    Note that using this approach also has a slight advantage in maintainability: it sets the options more clearly apart from the main positional argument.

    By the way, you or your team might feel that three is not the most appropriate threshold for deciding to use named arguments, but try to avoid significantly larger values of “three”. Most of the advantages of named arguments will be lost if you still have to plough through five or six positional arguments first.

    Please check back next week for the continuation of this article. 


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