Stats

160 Contributors: 9
2017-06-22
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

True and false

Download perl eBook

Syntax

  • undef # False
  • '' # Defined, False
  • 0 # Defined, Has Length, False
  • '0' # Defined, Has Length, False

Remarks

Perl does not have a boolean data type, nor does it have any true and false keywords like many other languages. However, every scalar value will evaluate to true or false when evaluated in a boolean context (the condition in an if statement or a while loop, for example).

The following values are considered false:

  • '', the empty string. This is what the built-in comparison operators return (e.g. 0 == 1)
  • 0, the number 0, even if you write it as 000 or 0.0
  • '0', the string that contains a single 0 digit
  • undef, the undefined value
  • Objects that use overloading to numify/stringify into false values, such as JSON::false

All other values are true:

  • any non-zero number such as 1, 3.14, 'NaN' or 'Inf'
  • any string that is numerically 0 but not literally the string '0', such as '00', '0e0', "0\n" and "abc".
    If you are intentionally returning a true numerically 0 value, prefer '0E0' (used by well known modules) or '0 but true' (used by Perl functions)
  • any other string that is not empty, such as ' ', 'false'
  • all references, even if they reference false values, such as \'', [], or {}
  • an array or hash of false values

The following operators are commonly treated to return a boolean in scalar context:

  • @a returns whether the array is empty or not

  • %h returns whether the hash is empty or not

  • grep returns whether any matching items were found or not

  • @a = LIST and (LIST) = LIST return whether the right-hand side LIST produced any scalars or not

Related Examples