Документация
HTML CSS PHP PERL другое

Section 2.21.  Lists

 
Previous
Table of Contents
Next

2.21. Lists

Parenthesize long lists.

The comma operator is really an operator only in scalar contexts. In lists, the comma is an item separator. Consequently, commas in multiline lists are best treated as item terminators. Moreover, multiline lists are particularly easy to confuse with a series of statements, as there is very little visual difference between a , and a ;.

Given the potential for confusion, it's important to clearly mark a multiline list as being a list. So, if you need to break a list across multiple lines, place the entire list in parentheses. The presence of an opening parenthesis highlights the fact that the subsequent expressions form a list, and the closing parenthesis makes it immediately apparent that the list is complete.e

When laying out a statement containing a multiline list, place the opening parenthesis on the same line as the preceding portion of the statement. Then break the list after every comma, placing the same number of list elements on each separate line and indenting those lines one level deeper than the surrounding statement. Finally, outdent the closing parenthesis back to the same level as the statement. Like so:


    my @months = qw(
        January   February   March
        April     May        June
        July      August     September
        October   November   December
    );

    for my $item (@requested_items) {
        push @items, (
            "A brand new $item",
            "A fully refurbished $item",
            "A ratty old $item",
        );
    }

    print (
        'Processing ',
        scalar(@items),
        ' items at ',
        time,
        "\n",
    );

Note that the final item in the list should still have a comma, even though it isn't required syntactically.

When writing multiline lists, always use parentheses (with K&R-style bracketing), keep to the same number of items on each line, and remember that in list contexts a comma isn't an operator, so the "break-before-an-operator rule" doesn't apply. In other words, not like this:

    my @months = qw( January   February   March   April   May   June   July   August
                     September   October   November   December
                    );

    for my $item (@requested_items) {
        push @items, "A brand new $item"
                   , "A fully refurbished $item"
                   , "A ratty old $item"
                   ;
    }

    print 'Processing '
          , scalar(@items)
          , ' items at '
          , time
          , "\n"
          ;

The "Thin Commas" guideline in Chapter 4 presents several other good reasons for parenthesizing lists.

    Previous
    Table of Contents
    Next
    © 2000- NIV