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

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

( #291339=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > Why does $string++ work the way it does? 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.

Comment on Answer: Why does $string++ work the way it does?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2015-07-04 14:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls