Operations, like fetching a value, modifying it, or storing it, are very common, so there’s a special syntax for them. Generally
$a = $a <some operator> $b;
can be written as
$a <some operator>= $b;
For instance, we could rewrite the preceding example as follows:
$a = 6 * 9;
This works for**=,*=,+=,-=,/=,.=,%=,&=,|=,^=,<<=,>>=,&&=, and||=. These all have the same precedence as the assignment operator=.
Autoincrement and Autodecrement
There are also two more operators,++and--. They add and subtract one from the variable, but their precedence is a little strange. When they precede a variable, they act before everything else. If they come afterwards, they act after everything else. Let’s examine these in the following example:
$a = 4;
You should see the following output:
$ perl auto1.pl
Let’s work this through a piece at a time. First we set up our variables, giving the values4and10to$aand$brespectively:
$a = 4;
In the following line, the assignment happens before the increment—this is known as a post-increment. So$bis set to$a’s current value,4, and then$ais autoincremented, becoming 5.
$b = $a++;
In the next line however, the incrementing takes place first—this is known as a pre-increment.$ais now 6, and$bis set to twice that, 12.
$b= ++$a * 2;
Finally,$bis decremented first (a pre-decrement), and becomes 11.$ais set to$bplus 4, which is 15.
$a= --$b + 4;
The autoincrement operator actually does something interesting if the variable contains a string of only alphabetic characters, followed optionally by numeric characters. Instead of converting to a number, Perl “advances” the variable along the ranges a–z, A–Z, and 0–9. This is more easily understood from a few examples:
$a = "A9"; print ++$a, "\n";
$ perl auto2.pl
This shows that a 9 turns into a 0 and increments the next digit left. Azturns into ana and increments the next digit left, and if there are no more digits to the left, either ana or anAis created depending on the case of the current leftmost digit.
Please check back next week for the conclusion to this article series.
blog comments powered by Disqus