Would be someone please to explain the next:
In the “Programming Perl” book postfix autoincrement operator is described, as
when placed after, they (
$a--,$a++) increment or decrement the variable after returning the value.
So, as I understood, $a++ is never used in void context, cause there has been said that
they increment or decrement the variable
But in the next example value of the variable never changes:
my $a = 3;
$a = $a++;
say $a; #always outputs 3
So my assumption is that there is no reason to use post-autoincrement when value is assigned to the same variable, but then the definition from the “Programming Perl” should be considered wrong, cause operator does not affect variable, but value in variable (at least in that example). Is that right?
Appreciation in advance.
Why, both postfix autoincrement and autodecrement operators are actually quite often used in void context exactly because they affect the variable – not the value.
Your example works the way it works because variable gets post-incremented before its old value gets assigned to it. In other words, the order of
…is…
Should you replace
$a = $a++with$b = $a++in your example, and print values of $b and $a afterwards, you’ll clearly see the difference: while$abecomes incremented (thus, equal to 4),$bgets assigned the old value of$a(3).