Section 2.4. Builtins


2.4. Builtins

Don't use unnecessary parentheses for builtins and "honorary" builtins.

Perl's many built-in functions are effectively keywords of the language, so they can legitimately be called without parentheses, except where it's necessary to enforce precedence.

Calling builtins without parentheses reduces clutter in your code, and thereby enhances readability. The lack of parentheses also helps to visually distinguish between subroutine calls and calls to builtins:

      while (my $record = <$results_file>) {         chomp $record;         my ($name, $votes) = split "\t", $record;         print 'Votes for ',               substr($name, 0, 10),       
# Parens needed for precedence
": $votes (verified)\n"; }

Certain imported subroutines, usually from modules in the core distribution, also qualify as "honorary" builtins, and may be called without parentheses. Typically these will be subroutines that provide functionality that ought to be in the language itself but isn't. Examples include carp and croak (from the standard Carp modulesee Chapter 13), first and max (from the standard List::Util modulesee Chapter 8), and prompt (from the IO::Prompt CPAN modulesee Chapter 10).

Note, however, that in any cases where you find that you need to use parentheses in builtins, they should follow the rules for subroutines, not those for control keywords. That is, treat them as subroutines, with no space between the builtin name and the opening parenthesis:

      while (my $record = <$results_file>) {         chomp( $record );         my ($name, $votes) = split("\t", $record);         print(             'Votes for ',             substr($name, 0, 10),             ": $votes (verified)\n"         );     } 

Don't treat them as control keywords (by adding a trailing space):

     while (my $record = <$results_file>) {         chomp ($record);         my ($name, $votes) = split ("\t", $record);         print (             'Votes for ',             substr ($name, 0, 10),             ": $votes (verified)\n"         );     } 



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net