WTF is “0 but true”
--
I have spent most of my life coding with JavaScript. For me, it is natural to use, and I know by heart most of its quirks and oddities. I understand many of these are quite strange for newcomers and can generate some aversion. However, recently learnt about one of these things in Perl that makes JavaScript oddities look amateurish.
Perl? What is that?
Perl is a scripting programming language that was quite popular in the early ’90s and lately has fallen in usage, although at the moment of writing it is still in the top 20 in the TIOBE index. It is still widely used in bioinformatics, sysops and projects like git or the Linux kernel among many others. Perl is well known for its concise although often cryptic syntax and powerful one-liners and regular expressions. This is also its curse as it has been accused of being hard to maintain and “write-only”.
Perl shares many similarities with languages like Python, JavaScript or PHP. Its variables may have different types, each one of them prefixes the variables names with a different sigil, similar to PHP: $scalar
and list, which may be @array
or %hash
.
Understanding Perl
The scalar represents a single value, that can be a string, a number, a float, or a reference to a list. We will not get deep into this, but the important idea is that Perl will transform between these different values depending on its needs as other scripting languages do. However, this sometimes is not explicit and it will complain if you use the wrong operator with the wrong type.
0> my $aString = "string"
$res[1] = "string"
1> $aString == "string" ? "true" : "false";
Argument "string" isn't numeric in numeric eq (==) at reply input line 1.
Argument "string" isn't numeric in numeric eq (==) at reply input line 1.
$res[2] = "true"
3> $aString eq "string" ? "true" : "false";
$res[3] = "true"
In the example above, we can see that Perl complained because we used a numeric operator instead of a string operator. Typically, we would execute the script in strict mode without warnings, which will give an error and stop execution.
Perl does not have a boolean type, but different values will be evaluated as “true” or “false”. Quoting the official documentation: