Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2016-05-30 03:49 GMT
Find Nodes?
    Voting Booth?