Why does !1 give me nothing in Perl?

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.

Leave a Comment