Perl Best Practices [Electronic resources]

Damian Conway

نسخه متنی -صفحه : 317/ 66
نمايش فراداده

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.