Приглашаем посетить
Радищев (radischev.lit-info.ru)

Section 2.6.  Operators

Previous
Table of Contents
Next

2.6. Operators

Use whitespace to help binary operators stand out from their operands.

Long expressions can be hard enough to comprehend without adding to their complexity by jamming their various components together:

    my $displacement=$initial_velocity*$time+0.5*$acceleration*$time**2;

    my $price=$coupon_paid*$exp_rate+(($face_val+$coupon_val)*$exp_rate**2);

Give your binary operators room to breathe, even if it requires an extra line to do so:


    my $displacement
        = $initial_velocity * $time  +  0.5 * $acceleration * $time**2;

    my $price
        = $coupon_paid * $exp_rate  +  ($face_val + $coupon_paid) * $exp_rate**2;

Choose the amount of whitespace according to the precedence of the operators, to help the reader's eyes pick out the natural groupings within the expression. For example, you might put additional spaces on either side of the lower-precedence + to visually reinforce the higher precedence of the two multiplicative subexpressions surrounding it. On the other hand, it's quite appropriate to sandwich the ** operator tightly between its operands, given its very high precedence and its longer, more easily identified symbol.

A single space is always sufficient whenever you're also using parentheses to emphasize (or to vary) precedence:


    my $velocity
        = $initial_velocity + ($acceleration * ($time + $delta_time));

    my $future_price
        = $current_price * exp($rate - $dividend_rate_on_index) * ($delivery - $now);

Symbolic unary operators should always be kept with their operands:


    my $spring_force = !$hyperextended ? -$spring_constant * $extension : 0;

    my $payoff = max(0, -$asset_price_at_maturity + $strike_price);

Named unary operators should be treated like builtins, and spaced from their operands appropriately:


    my $tan_theta = sin $theta / cos $theta;

    my $forward_differential_1_year = $delivery_price * exp -$interest_rate;

    Previous
    Table of Contents
    Next