cirne100
cirne100

Reputation: 1558

Increment (++) and decrement (--) strings in 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?

Upvotes: 27

Views: 16282

Answers (3)

Chas. Owens
Chas. Owens

Reputation: 64929

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.

Upvotes: 9

mob
mob

Reputation: 118605

Perl give us lots of facilities, why not this one?

Because it is not intuitive what values should precede the "lowest" character in range. It may make sense that "A" + 1 should be "B", and that "B" + 1 should be "C". And therefore "B" - 1 should be "A". But what should "A" - 1 be?

Upvotes: 7

nandhp
nandhp

Reputation: 4817

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

Upvotes: 27

Related Questions