Item 10: Avoid excessive punctuation.


Perl programs tend to be filled with punctuation. Excessive punctuation makes programs less readable, and wise programmers will take advantage of features that make it possible to write programs with considerably less punctuation. For example, Perl allows user -written functions to use the same ampersand-less syntax that built-in functions do:

Different kinds of function call syntax

 sub myfunc { ... }; 
 
 &myfunc(1, 2, 3); 

Old-style, explicit ampersand.

 myfunc(1, 2, 3); 

No ampersand.

 myfunc 1, 2, 3; 

Works if myfunc has already been declared.

The traditional & syntax has its usesit's the only way to call a subroutine whose name is a keyword, for example, &for . The list operator syntax, without ampersand or parentheses, works if the definition or declaration of the function appears lexically before the function call. This is generally fine, but there are some pitfalls:

 myfunc 1, 2, 3;  sub myfunc { }; 

ERRORcan't use as list operator before definition.

 myfunc 1, 2, 3;  BEGIN { sub myfunc { } }; 

ERRORdefinition must lexically precede use.

 eval "sub myfunc {}";  myfunc 1, 2, 3; 

ERRORand it must also be present at compile time.

 BEGIN { eval "sub myfunc {}" }  myfunc 1, 2, 3; 

OKbut strange .

Another helpful feature is the addition of the super-low precedence short-circuit logical operators and and or . (There's also the less exciting not and the generally useless xor .) These allow you to get rid of parentheses in a variety of situations:

Use and and or instead of && and .

The and and or operators allow you to omit parentheses around list operators, assignment, and binding.

 print "hello, " && print "goodbye.";  print "hello, " and print "goodbye."; 

WRONG goodbye.1

OK hello, goodbye.

 $size = -s $file or    die "$file has zero size.\n"; 

die if file has zero size.

 $word =~ /magic/ or $mode = 'peon'; 

$mode = 'peon' unless $word =~ /magic/;

Remember that you can always eliminate a semicolon preceding a closing brace . This is probably a good idea in blocks that consist of a single statement, especially when such a block is used as an argument to map , grep , do , eval , or the like:

 @caps = map { uc $_; } @words; 

Unnecessary semicolon.

 @caps = map { uc $_ } @words; 

Looks cleaner.

One more way to get rid of extra parentheses and braces is to use the statement modifier, or " backwards conditional," syntax. It's handy once you get used to it:

 if (/^END$/) { last } 

Mundane.

 last if /^END$/; 

Doesn't this look better?



Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

Similar book on Amazon

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