Boolean Context
Another special don’t-care scalar context is called Boolean
context. Boolean context is simply any place where an
expression is being evaluated to see whether it’s true or false.
When we say “true” and “false” in this book, we mean the technical
definition that Perl uses: a scalar value is true if it is not the
null string "" or the number 0
(or its string equivalent, "0").
A reference is always true because it represents an address that is
never 0. An undefined value (often called undef) is always false because it looks
like either "" or 0, depending on
whether you treat it as a string or a number. (List values have no
Boolean value because list values are never produced in scalar
context!)
Because Boolean context is a don’t-care context, it never
causes any scalar conversions to happen, though of course the scalar
context itself is imposed on any operand that cares. And for many
operands that care, the scalar they produce in scalar context
represents a reasonable Boolean value. That is, many operators that
would produce a list in list context can be used for a true/false
test in Boolean context. For instance, in list context such as that
provided by the unlink operator, an array name produces the list of its
values:
unlink @files; # Delete all files, ignoring errors.
But if you use the array in a conditional (that is, in a Boolean context), the array knows it’s in scalar context and returns the number of elements in the array, which conveniently is true so long as ...
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