On Jun 3, Abdulaziz Ghuloum said:
>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:
Here's the short answer:
Auto-increment (++) is magical for strings; auto-decrement is not.
What does "magical" mean? It means that you can go from "perl" to
"pern" in two easy steps:
$x = "perl";
$x++;
$x++;
print $x;
Note that you can't use $x += 2 there, since that is numerical addition,
not the magical auto-increment operator.
>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).
Or just read 'perldoc perlop' for the information about ++ vs. --
Auto-increment and Auto-decrement
"++" and "--" work as in C. That is, if placed before a
variable, they increment or decrement the variable before
returning the value, and if placed after, increment or
decrement the variable after returning the value.
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]*$/, 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'
The auto-decrement operator is not magical.
It even tells you HOW the string must match in order to be treated as a
string for auto-increment's magic. "a11" is valid, but "a1a" is not.
As to why -- is not magical, what is "a"--? "-a"? Maybe. But then,
"aa"-- is "z", so why isn't "a"-- ""?
It's confusing, and hardly useful. Magical ++ is more useful.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
Are you a Monk? http://www.perlmonks.com/ http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc. http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter. Brother #734
** Manning Publications, Co, is publishing my Perl Regex book **