Why is '0' false in Perl?

后端 未结 6 1679
故里飘歌
故里飘歌 2021-01-05 02:14

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.

6条回答
  •  时光说笑
    2021-01-05 02:18

    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.

提交回复
热议问题