With perl -e '$string="a";print ++$string;'
we get b
,
but with perl -e '$string="b";print --$string;'
we get -1
.
So, if we can increment why can't we decrement?
EDITED
"The auto-decrement operator is not magical" by perlop
Perl give us lots of facilities, why not this one? This is not criticism, but wouldn't be expected similar behavior for similar operators? Is there any special reason?
Perl also provides ++ the auto increment, and -- auto decrement operators. They increase and decrease respectively the value of a scalar variable by 1. Both the postfix versions $x++, $x-- and the prefix versions ++$x, --$x and they behave the same way as in other languages.
The ++ and -- operators are used with a variable to increment or decrement that variable by 1 (that is, to add or subtract 1). And as with C, both operators can be used either in prefix fashion (before the variable, ++$x) or in postfix (after the variable, $x++).
Just as with the =~ regex match operator, the left side is the "subject" of the match, and the right side is the "pattern" to match against -- whether that be a plain scalar, a regex, an array or hash reference, a code reference, or whatever.
The range operator is used as a shorthand way to set up arrays.
perlop(1) explains that this is true, but doesn't give a rationale:
The auto-increment operator has a little extra builtin magic to it. [If applicable, and subject to certain constraints,] the increment is done as a string, preserving each character within its range, with carry[...]
The auto-decrement operator is not magical.
The reason you get -1 is because when interpreted as a number, "b" turns into 0 since it has no leading digits (Contrarily, "4b" turns into 4).
There are at least three reasons:
Raku (née Perl 6) on the other hand does not suffer from a need for backwards compatibility, and therefore has better behavior for auto-incrementing strings and has auto-decrementing as well. The ++ and -- operators work by calling the succ
and pred
methods on the object they are operating on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With