Why does !1 give me nothing in Perl?

前端 未结 5 1641
青春惊慌失措
青春惊慌失措 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:31

    Be careful: what you've written isn't doing what you think it's doing. Remember, perl has no real boolean datatype. It's got scalars, hashes, lists, and references. The way it handles true/false values, then, is contextual. Everything evaluates to "true" in perl except for undefined variables, the empty list, the empty string, and the number 0.

    What your code is doing, then, is taking the inverse of a value that evaluates to "false", which can be anything which is not in the list above. By convention and for simplicity's sake, perl returns 1 (though you should not rely on that; it could very well return a list containing a series of random numbers, because that will evaluate to "true" as well.)

    A similar thing happens when you ask for the inverse of a value that evaluates to "true." What's actually being printed out is not "nothing," it's the empty string (''), which, as I mentioned, evaluates to "false" in boolean expressions. You can check this:

    print "This evaluates to false\n" if( (!1) eq '');
    

    If you're asking for why perl spits out the empty string instead of one of the other "false" values, well, it's probably because perl is made to handle strings and that's a perfectly reasonable string to hand back.

提交回复
热议问题