First of all, I come from C, Java, Python background. Recently, I started learning Perl for my new job and I got curious about '0'
(0-string) being false.
I've read that this particular behaviour is the reason why Perl had to have <>
operator for reading files so it feels more like a design flaw to me than anything right now. However, I also know that Perl is a mature language and I am guessing this behaviour has its uses otherwise it would have been fixed long time ago.
So in what cases would '0'
= false be useful?
If you read that it has anything to do with <>
, you are reading bad sources; I can't imagine where that claim would come from.
'0' is false because almost everywhere perl doesn't distinguish between numbers stored in numeric form and in string form; doing so in boolean tests would run against this grain.
In languages (Python, Javascript?) where '0' is true, I find it odd that '' is false; why make an exception for one string but not the other?
Perl has no explicit typing, and its interpretation of type is highly context-dependent. For example:
$a = "2b";
$b = "3a";
$c = $a + $b;
print $c;
yields 5.
on the other hand...
$a = "b2";
$b = "3a";
$c = $a + $b;
print $c;
yields 3.
and...
$a = "b2";
$b = "3a";
$c = $a.$b;
print $c;
yields b23a
So "'0' (string)" is not a string, or a number, or a bool, until you use it, and then it can be any of those things, determined by its use. Type is not determined until you try to operate. Then Perl assesses the context to endeavour your intention and acts accordingly. This is a Feature, and why there are Many Ways to Do Things in Perl. It can of course lead to a plenty of confusing code but is excellent for 1-liners, obfuscation and Perl golf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With