Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment (++) and decrement (--) strings in Perl

Tags:

perl

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?

like image 732
cirne100 Avatar asked Jun 23 '11 17:06

cirne100


People also ask

Can you use ++ in Perl?

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.

What is++ in Perl?

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++).

What does ~~ mean in Perl?

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.

What is range operator in Perl?

The range operator is used as a shorthand way to set up arrays.


2 Answers

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).

like image 134
nandhp Avatar answered Sep 22 '22 02:09

nandhp


There are at least three reasons:

  1. because there isn't any great need for it
  2. the magic of auto-incrementing has been seen to be faulty, and there is no reason implement auto-decrementing in the same faulty way
  3. the magic of auto-incrementing cannot be fixed because p5p doesn't like to break backwards compatibility

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.

like image 31
Chas. Owens Avatar answered Sep 24 '22 02:09

Chas. Owens