First let's make clear that I am not using a cheap and dirty trick depending on approximation on floating point calculations or the surprise of unexpected operator precedence.
The demonstration depends on another paradoxical fact: We show that a string can be both == 0 and != 0.
Proof:
So we got 0 == "one" and "one != 0 so 0 != 0. The paradox is due to the fact that the string is not a numerical string... Even if I deliberately make that string the name of a number.print qq|"one" == 0| if "one" == 0; # prints: "one" == 0 print qq|"one" != 0| if "one" ; # prints: "one" != 0
A non numerical string non empty string is deemed non null in boolean context. This makes easy to test if a string is not empty and not the canonical decimal representation of 0. "0" is canonical; "00" is not! We make the economy of using the length operator:
print "non null" if $str;
print "non null" if length $str;
When needed for an arithmetic operation, Perl silently converts a string representing a number in decimal or hexadecimal to its value.
print "0x23" + 0
print "23" + 0
What worries me more is that, even in strict mode, perl silently convert to 0 a string that is not a valid representation of any number. My demonstration relies on this shortcoming
Anyway, Perl has the right stand between opposite evil "incarnated" by C++ and Java (as shown below), that is between too much implicit conversions between types or not enough. In fact, when doing arithmetics, the perl programmer does not have to think if he uses a string representing a number or deals with a number or a boolean. This is somewhat dangerous so, he may forget that if wants to deal with strings instead of numbers, he has to use string operators (say eq instead of ==. But the alternative, making explicit conversions between numbers and strings is so painful that this danger is a small price to pay.
Even if C++ does not provide any implicit conversion from string to number, the conversion rules between types are complex especially if one (ab)uses user defined conversions.
In Java, you must painfully specify everything explicutely. Dont you hate to have to type if ( a != 0 ) { ... } because there is no implicit conversion from integer to boolean. Or so it was last time I checked.
Note: on the first edition of that node I posted nonsensical code that was correctly pointed wrong. With the "correct code" I stand to my original argument.
-- stef
In reply to in Perl 0 != 0 ... and this is good by stefp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |