Section 4.17. Lists


4.17. Lists

Parenthesize every raw list.

The precedence of the comma operator is so low that, even when it's in a list context, it may not act the way that a casual reader expects. For example, the following assignment:

     @todo = 'Patent concept of 1 and 0', 'Sue Microsoft and IBM', 'Profit!';

is identical to:

     @todo = 'Patent concept of 1 and 0';     'Sue Microsoft and IBM';     'Profit!';

That's because the precedence of the comma is less than that of assignment, so the previous example is really a set of "junior semicolons":

     (@todo = 'Patent concept of 1 and 0'), 'Sue Microsoft and IBM', 'Profit!';

For that reason it's a good practice to ensure that comma-separated lists of values are always safely enclosed in parentheses, to boost the precedence of the comma-separators appropriately:

      @todo = ('Patent concept of 1 and 0', 'Sue Microsoft and IBM', 'Profit!');

But be careful to avoid the all-too-common error of using square brackets instead of parentheses:

     @todo = ['Patent concept of 1 and 0', 'Sue Microsoft and IBM', 'Profit!'];

This example produces a @todo array with only a single element, which is a reference to an anonymous array containing the three strings.



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