Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Subroutines > Argument Lists

Argument Lists

Always unpack @_ first.

Subroutines always receive their arguments in the @_ array. But accessing them via $_[0], $_[1], etc. directly is almost always a Very Bad Idea. For a start, it makes the code far less self-documenting:

Readonly my $SPACE => q{ };

# Pad a string with whitespace...
sub padded {
    # Compute the left and right indents required...
    my $gap   = $_[1] - length $_[0];
    my $left  = $_[2] ? int($gap/2) : 0;
    my $right = $gap - $left;

    # Insert that many spaces fore and aft...
    return $SPACE x $left
         . $_[0]
         . $SPACE x $right;
}

Using "numbered parameters” like this makes it difficult to determine what each argument is used for, whether they’re being used in the correct order, and whether the computation they’re used in is algorithmically sane. Compare the previous version to this one:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint