Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, the following code:
$a = 'a'; while(length($a) < 3) { print $a++, "\n"; }
prints out 'a' to 'z', and then 'aa', 'ab', to 'az'. How does this work? (1) it looks like it's doing character arithmetic, but why stopps at 'z'? (2) if I change first line to $a='A', it will do the same iteration only with capital letters, why not iterate through all ascii? (3) if I replace $a++ by $a = $a+1, then it prints 1,2,..10. What's the different between increments and assignment here?

Replies are listed 'Best First'.
Re: Strange character arithemtic
by toolic (Bishop) on Jan 19, 2014 at 23:16 UTC
    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

    Super Search

Re: Strange character arithemtic
by choroba (Cardinal) on Jan 19, 2014 at 23:19 UTC
    It is documented in perlop, in 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
    ...
    The auto-decrement operator is not magical.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Strange character arithemtic
by AnomalousMonk (Archbishop) on Jan 19, 2014 at 23:27 UTC

    Regarding question 3: Perl does its level best to convert a string to a number in numeric context, as supplied by the addition (not assignment) operator. Example of behavior in this context (with warnings, which you obviously wern't using):

    >perl -wMstrict -le "for my $string (qw(x 1x 12x 987x)) { print qq{string '$string' in numeric context is == }, 0+$string; } " Argument "x" isn't numeric in addition (+) at -e line 1. string 'x' in numeric context is == 0 Argument "1x" isn't numeric in addition (+) at -e line 1. string '1x' in numeric context is == 1 Argument "12x" isn't numeric in addition (+) at -e line 1. string '12x' in numeric context is == 12 Argument "987x" isn't numeric in addition (+) at -e line 1. string '987x' in numeric context is == 987

    See Scalar values in perldata.