What Is Truth?
We’ve bandied about the term truth,[28] and we’ve mentioned that certain operators return a true or a false value. Before we go any further, we really ought to explain exactly what we mean by that. Perl treats truth a little differently than most computer languages, but after you’ve worked with it a while, it will make a lot of sense. (Actually, we hope it’ll make a lot of sense after you’ve read the following.)
Basically, Perl holds truths to be self-evident. That’s a glib way of saying that you can evaluate almost anything for its truth value. Perl uses practical definitions of truth that depend on the type of thing you’re evaluating. As it happens, there are many more kinds of truth than there are of nontruth.
Truth in Perl is always evaluated in scalar context. Other than that, no type coercion is done. So here are the rules for the various kinds of values a scalar can hold:
Any string is true except for
""and"0".Any number is true except for 0.
Any reference is true.
Any undefined value is false.
Actually, the last two rules can be derived from the first two. Any reference (rule 3) would point to something with an address and would evaluate to a number or string containing that address, which is never 0 because it’s always defined. And any undefined value (rule 4) would always evaluate to 0 or the null string.
And, in a way, you can derive rule 2 from rule 1 if you pretend that everything is a string. Again, no string coercion is actually done to evaluate truth, but ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access