Why does !1 give me nothing in Perl?

前端 未结 5 1640
青春惊慌失措
青春惊慌失措 2020-12-03 14:29

This is strange. The following:

$sum = !0;
print $sum;

prints out 1 as you would expect. But this

$sum = !1;
print $sum;
         


        
5条回答
  •  再見小時候
    2020-12-03 14:38

    See perldoc perlsyn:

    Truth and Falsehood

    The number 0, the strings '0' and '' , the empty list () , and undef are all false in a boolean context. All other values are true. Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as '' , but as a number, it is treated as 0.

    There, if you print the value as a number, you will get 0 rather than the empty string:

    printf "%d\n", $_ for map { !$_ } (1, 0);
    

    or

    print 0 + $_, "\n" for map { !$_ } (1, 0);
    

    Compare those to

    printf "%s\n", $_ for map { !$_ } (1, 0);
    

    and

    print $_, "\n" for map { !$_ } (1, 0);
    

提交回复
热议问题