"+=" and friends

Contents | Up | Prev | Next

# 4.1. "+=" and friends

Perl provides a shortcut for writing "$myvar = $myvar + $value", or "$myvar = $myvar / $value" and similar operations. Here's an example:

    $a = 1;
    $b = 0;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b += 1;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b += 1;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b += 1;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b += 1;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b += 1;
    print "2^", $b, "=", $a, "\n";

Since the operations `$a += 1` and `$a -= 1` are so commonly used, they were also assigned a separate operator. One can use `$a++` and `$a--` to perform them. For example, the above program could have been written as:

    $a = 1;
    $b = 0;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b++;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b++;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b++;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b++;
    print "2^", $b, "=", $a, "\n";
    $a *= 2; $b++;
    print "2^", $b, "=", $a, "\n";

Contents | Up | Prev | Next