"Perl for Perl Newbies" - Part 1Variables"+=" and friends

4.1. "+=" and friends

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

$x =
1;
$y =
0;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y +=
1;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y +=
1;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y +=
1;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y +=
1;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y +=
1;
print
"2^",
$y,
"=",
$x,
"
\n
";

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

$x =
1;
$y =
0;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y++;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y++;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y++;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y++;
print
"2^",
$y,
"=",
$x,
"
\n
";
$x *=
2;
$y++;
print
"2^",
$y,
"=",
$x,
"
\n
";

Written by Shlomi Fish