Edward Barnard
Edward Barnard

Reputation: 356

Why does perl string auto-increment magic behavior exist?

In perl, the string "aa" can be auto-incremented to become "ab" when various specific conditions are met. PHP has similar behavior, and references Perl, which I take to mean that the earlier use is with Perl.

Why was the magic behavior added to Perl in the first place?

An example discussion is here: Increment (++) and decrement (--) strings in Perl which notes that the perl docs do not give a rationale.

And that's my question: What was the original rationale behind creating the string auto-increment "magic" behavior?

2ND EDIT: This has nothing to do with autovivification. In researching possible answers to my rationale question, I misinterpreted what I was reading. Thanks ThisSuitIsBlackNot for pointing that out, and choroba for asking what I meant.

I completely agree that the feature IS useful, and I do use it whenever I make a reasonable excuse to do so, primarily as a generator of unique non-numeric tags/keys. I'm still wondering if there WAS a specific rationale or use case it was originally aimed at. We may never know!

Upvotes: 0

Views: 222

Answers (3)

Borodin
Borodin

Reputation: 126742

I suggest that it is there just because it is useful, and that it is no more magical than the simple integer increment

I have no idea of the truth, but I can imagine that, while Perl was in development, the programmers came across the problem of what to do when applying ++ to a scalar variable that contains only a string. And, rather than raise an exception, someone decided that it would be good to implement string incrementation

Many things in programming are sequenced in exactly this fashion, and someone — maybe Larry — thought it would be a Good Idea to build that facility into the language. It is the sort of facility that may seem worthless until you need it, after which it is invaluable. Would you like to code that for yourself, and override the ++ operator?

I find it very useful, and I guess I use it up to a dozen times a year, all for different reasons. I tried to search my software archive but it's a hard thing to find by string match!

Upvotes: 4

ikegami
ikegami

Reputation: 386331

Why was the magic behavior added to Perl in the first place?

Because it is useful. At the very least, it can be used to create non-numeric unique ids.

The most likely explanation that I can find is to support autovivication.

There's no relation between it and autovivification or references in general.

That is, it's relatively common to auto-increment a generated hash key.

Sure, if string ++ is used create unique ids, you might use a hash to lookup by id.

Upvotes: 5

choroba
choroba

Reputation: 241968

Maybe to make emulation of split easy?

Upvotes: 1

Related Questions