Autoincrementing letters in Perl

Viewed 8126

I do not understand autoincrementing letters in Perl.

This example seems perfectly understandable:

$a = 'bz'; ++$a;
ca #output

b gets incremented to c. There is nothing left for z to go to, so it goes back to a (or at least this is how I see the process).

But then I come across statements like this:

$a = 'Zz'; ++$a;
AAa #output

and:

$a = '9z'; ++$a;
10 #output

Why doesn't incrementing Zz return Aa? And why doesn't incrementing 9z return 0z?

Thanks!

6 Answers

=> In case of alpha-numeric strings starting with a character like 'bz' or 'Zz' start moving from the right.The first character is 'z'.As you say there is nowhere for 'z' to increment so it increments to 'a' but an extra carry is given over to the next digit on the left.So 'b' increments to 'c'. Now in the second case Z does not see any alphabet to the left of it.In such cases an extra copy of the current digit is created as it gets incremented.

=> In case of alpha-numeric strings starting with a digit like '9z', perl considers it as a mistake made by the user and considers it as the number which precedes the string (in this case 9) and increments the number. So 9 becomes 10.

Plz. correct me if I am wrong

Related