Previous Page
Next Page

2.15. Vertical Alignment

Align corresponding items vertically.

Tables are another familiar means of chunking related information, and of using physical layout to indicate logical relationships. When setting out code, it's often useful to align data in a table-like series of columns. Consistent indentation can suggest equivalences in structure, usage, or purpose.

For example, initializers for non-scalar variables are often much more readable when laid out neatly using extra whitespace. The following array and hash initializations are very readable in tabular layout:


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

    my %expansion_of = (
        q{it's}    => q{it is},
        q{we're}   => q{we are},
        q{didn't}  => q{did not},
        q{must've} => q{must have},
        q{I'll}    => q{I will},
    );

Compressing them into lists saves lines, but also significantly reduces their readability:

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

    my %expansion_of = (
        q{it's} => q{it is}, q{we're} => q{we are}, q{didn't} => q{did not},
        q{must've} => q{must have}, q{I'll} => q{I will},
    );

Take a similar tabular approach with sequences of assignments to related variables, by aligning the assignment operators:


    $name   = standardize_name($name);
    $age    = time - $birth_date;
    $status = 'active';

rather than:

    $name = standardize_name($name);
    $age = time - $birth_date;
    $status = 'active';

Alignment is even more important when assigning to a hash entry or an array element. In such cases, the keys (or indices) should be aligned in a column, with the surrounding braces (or square brackets) also aligned. That is:


    $ident{ name   } = standardize_name($name);
    $ident{ age    } = time - $birth_date;
    $ident{ status } = 'active';

Notice how this tabular layout emphasizes the keys of the entries being accessed, and thereby highlights the purpose of each assignment. Without that layout, your attention is drawn instead to the "column" of $ident prefixes, and the keys are consequently much harder to discern:

    $ident{name} = standardize_name($name);
    $ident{age} = time - $birth_date;
    $ident{status} = 'active';

Aligning the assignment operators but not the hash keys is better than not aligning either, but still not as readable as aligning both:

    $ident{ name }   = standardize_name($name);
    $ident{ age }    = time - $birth_date;
    $ident{ status } = 'active';

    Previous Page
    Next Page