Reputation: 367
I've got a question in Perl studying.
$a = "Z9"; print ++$a;
It prints out AA0
. This can easily understood that 9 increased by 1 gets 10 and Z increased 1 gets AA. Just like 99+1.
But what happened if I flipped over Z and 9:
$a = "9Z"; print ++$a;
This will get 10
. Why the letter Z is gone? Where did it gone?
Regards, Neil
Upvotes: 1
Views: 135
Reputation: 35208
"9Z"
is interpreted like a number, and therefore the non-numeric ending gets truncated before the autoincrement. The same would be true of "9 the rest of this string is ignored"
.
This is similar to the way that print "2foo" + "2bar";
will output 4
.
The string magic that you observe with "Z9"
is documented in perlop #Auto-increment and Auto-decrement
The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern
/^[a-zA-Z]*[0-9]*\z/
, the increment is done as a string, preserving each character within its range, with carry:
print ++($foo = "99"); # prints "100"
print ++($foo = "a0"); # prints "a1"
print ++($foo = "Az"); # prints "Ba"
print ++($foo = "zz"); # prints "aaa"
Upvotes: 5