Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Answer: Why does $string++ work the way it does?

by davido (Archbishop)
on Sep 14, 2003 at 03:18 UTC ( #291339=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > Why does $string++ work the way it does? - Answer contributed by davido

The ++ operator can act upon both numbers and strings in a predictable fashion. With strings, 'A' increments to 'B', and 'Z' to 'AA'. ...and so on.

The magic of the ++ operator with respect to strings also exherts itself by providing the .. operator (range operator) with similar magic.

Try this at home...

my $x = 1; my $b = 'A'; $x++; # $x now equals 2. $b++; # $b now equals 'B'. my @numbers = (1..10); # @numbers now contains 1, 2, 3, .. 10. my @letters = ('A'..'Z'); # @letters now contains A, B, C, .. Z. my @more = ('A'..'AZ'); # @more now contains A, B, .. Z, AA, AB, ..AZ.

It seems that ++ magic, and .. magic, are related. Don't be fooled into expecting -- to be magic too though, it isn't. Neither can you use the .. operator alone to create descending lists.

my $b = 'Z'; $b--; # You don't get Y. my @array = (10..1); # You don't get 10, 9..1. my @letters = ('Z'..'A'); # You don't get the letters reversed.

Have fun with ++ and .. but take care not to expect magic from --. -- is for numbers.

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2018-05-24 21:56 GMT
Find Nodes?
    Voting Booth?