Re: perl 'advancing' variable facility..



On Wed, May 25, 2005 at 10:27:11AM +0000, Vineet Pande wrote:

> Hi:
> I don't understand the way perl 'advances' the variables along the range
> a-z, A-Z, and 0-9.
> For example from a book
>
> $a = "A9"; print ++$a, "\n";
>
> gives B0 as expected,
>
> but,
> $a = "Zz"; print ++$a, "\n";
>
> gives AAa.
>
> Why?? why not Aa only!

Because you get a carry, similar to the way 99 + 1 = 100, not 00.

> also $a = "9z"; print ++$a, "\n";
>
> gives 10.
> and why not 0a?

Because "9z" doesn't match the criteria for magic auto-increment.

perldoc perlop says:

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'

--
Paul Johnson - paul@xxxxxxxx
http://www.pjcj.net
.



Relevant Pages

  • Re: numeric - char
    ... The auto-increment operator has a little extra builtin magic ... If you increment a variable that is numeric, ... has ever been used in a numeric context, ... string contexts since it was set, and has a value that is ...
    (perl.beginners)
  • Re: help understanding ++
    ... 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 ... recognise the input to ++ as a number. ...
    (comp.lang.perl.misc)
  • help understanding ++
    ... 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 ...
    (comp.lang.perl.misc)
  • Re: help understanding ++
    ... > The auto-increment operator has a little extra builtin magic to it. ... > a numeric context, you get a normal increment. ... > has been used in only string contexts since it was set, ...
    (comp.lang.perl.misc)
  • Re: incr and single characters ...
    ... Snip from perl docs: ... If you increment a variable that is numeric, ... been used in a numeric context, ... great those differences in character can sometimes be. ...
    (comp.lang.tcl)