3 ms·
So what does Perl do with "jfm" + 3 that's so enormously funny?
by brazzy 17y ago
So what does Perl do with "jfm" + 3 that's so enormously funny?
- nostrademons 17y agoTry it: >>> perl -e 'print "jfm" + 3' 3 My guess is that it coerces "jfm" to an int (0), and then adds that to 3 to get 3.
- jerf 17y agoIt's a bit of a low blow on the author's part, as in perl, "+" is not "a generic addition operator that can be overloaded to concatenate strings", it is literally the "numeric addition operator" and both sides of the + will be coerced as needed to turn them into numbers. The default for strings is to parse them as numbers ("10" + "20" yields the number 30), and a string that doesn't start with a number defaults to zero. If Perl does anything wrong here, it is in not throwing a type error at runtime but just silently coercing the number. Compare with Python: Python 2.6.4 ... linux2 Type "help", ... >>> "30" + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects (Using "use overload" may let you do further crazy things with +; I'm just talking about the default definition of the operator.) Incidentally, the string equivalent of + is ".", the dot. There's a parallel hierarchy of operators in Perl for numbers vs. strings, which is part of why Perl has so damned many operators. Woe betide the developer that says "==" instead of "eq" accidentally....
- sundarurfriend 17y agoI actually like the fact that it has different operators for numbers and strings. It somehow feels cleaner to me, this separation of contexts (contexts in the usual sense of the word, not strictly Perl contexts). The fact that the string equivalents are all words (cmp, eq, ne, etc.) gives a useful mnemonic (strings usually contain 'words', so their operators are words), and also prevents ugliness from operator-proliferation - it's the symbol operators that usually make the code _look_ ugly and lead to claims of 'line noise'.
- chromatic 17y ago> It somehow feels cleaner to me, this separation of contexts (contexts in the usual sense of the word, not strictly Perl contexts). I've made the argument that the intended type of an operation is as much a context as the amount (void/scalar/list) context. The relevant Perl 5 literature flirts with that phrasing, but Perl 6 goes much further to extend that metaphor. That has proven very useful in discussions of consistency.