Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is '0' false in Perl?

Tags:

perl

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?

like image 395
GoldenD Avatar asked Jan 09 '13 01:01

GoldenD


2 Answers

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?

like image 123
ysth Avatar answered Sep 17 '22 16:09

ysth


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.

like image 31
foundry Avatar answered Sep 20 '22 16:09

foundry