Hello everybody

Incrementing and decrementing strings are quiet puzzling to me.  I don't seem
to figure out the rationale behind the use of the increment (++) and decrement
(--) operators when it comes to strings.  Let me illustrate:

$str = 'hello';
$str++;
print "$str\n"; # here we get "hellp".  Basically perl adds one to the letter
'o' making it 'p'
$str--;
print "$str\n"; # here we get -1 
                        # since the value of $str was 'hellp' 
                        # which is evaluated to 0, decremented to -1

$str = 'az';
$str++;
print "$str\n"; # what do we get?  'ba'  because 'z' is the last
                        # letter of the alphabet, so, z+1 = a and one at hand,
                        # adding it to 'a' to get 'ba'.  hmmm

$str = '1b';
$str++;
print "$str\n"; # we get 2 here, since '1b' =~ 1 when evaluated at a numeric
context

$str = 'b1';
$str++;
print "$str\n"; # what do we get here? 'b2'

$str = 'ab1';
$str++;
print "$str\n"; # can you take a guess?  Answer: 'ac0' 

$str = 'ab1a';
$str++;
print "$str\n"; # 'ab1a' evaluates to 0, so incrementing it gets us to 1

Maybe you can make out a rule for what happens in every case (just like the
nested if-statements in the code Perl_sv_inc at sv.c lines 4605-4725 of the
stable perl-5.6.1 distribution).

So, is there a rational reason why the increment operator should behave this
way and why the decrement operator behaves differently?

(maybe this was not a beginners question, but it may help eleminate some
possible future frustration).





_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com

Reply via email to