Perl Boolean

Perl doesn’t have boolean type. It will recognise the value from other types to determine whether it is false. The following values are considered false in Perl, other than that, all possible values are considered true:

  • ““, “0” (string)
  • 0 (integer)
  • 0.0 (float)
  • a zero sized array
  • an empty list
  • undef (means undefined)

Note: If the subroutine (sub) doesn’t return a value such as the following, then Perl will think that it is returning a false value due to #Autovivification. Which type of the value should it return is depending on where does the value is being used.

sub emptyReturn {
  return;  # return either "", "0", 0, 0.0 or undef
}

Perl treat different types differently regarding their booleaness. It is recommended to do a #Perl Type Conversion if necessary.

Note: Built-in Perl functions that return boolean will return integer 1 for true and an empty string (““) for false.

Links to this page
  • Perl Type Conversion

    This could be especially useful when trying to test a value’s booleaness# if it is of different type.

  • Perl Reference

    As shown, a Reference will be Autovivified# into string, which means that it can’t point to a string as it is a string itself. If it is evaluated, it will always return true#. To dereference it, we could add an extra $ to the reference:

  • Perl Hash

    Other than keys and values, Perl Hash stores a special variable called iterator that could be used by the each() to return a pair of key and value and then advance to the next pair. The function will return an empty list when it encountered no pair left after the current pair, which is recognised by the Perl Boolean# as false. Its usage could be as simple as iterating through the hash using a while loop, such as the following:

  • Perl Array

    To clear an array, assign array to an empty bracket like my @array = ();. Don’t define array as undef! It will fill up the array with undef elements which still counted as valid elements. An empty array returns an integer of 0, which is treated as false in terms of Perl Boolean#.

  • Autovivification

    Autovivification is a Perl term, stated if a variable hasn’t been created before being used by a function, then it will initialised as undef which means undefined. If such variable is being used in a function, it will be converted into 0 or an empty string (““), which means false# in Perl, depending on the context. It can be a good thing to have, but it is not for all situations. It is suggested to import standard libraries warnings and strict to show undefined variables as warnings when interpreted by Perl.

#perl