Examples of Boolean values in Perl programs

Examples illustrating concepts from
Computer Science & Perl Programming: Best of the Perl Journal
Edited by Jon Orwant
O'Reilly, 2003
Chapter 7: What is Truth, by Nathan Torkington

  1. #!/usr/bin/perl -w
    
    # Test the truth value of an undefined variable
    
    if ($x) {
      print '$x is defined'."\n";
    } else {
      print '$x is undefined'."\n";
    }
    
  2. #!/usr/bin/perl -w
    
    # Test the truth value of an empty string
    
    $x = "";
    if ($x) {
      print "an empty string is true\n";
    } else {
      print "an empty string is false\n";
    }
    
  3. #!/usr/bin/perl -w
    
    # Test the truth value of integer zero
    
    $x = 0;
    if ($x) {
      print "integer zero is true\n";
    } else {
      print "integer zero is false\n";
    }
    
  4. #!/usr/bin/perl -w
    
    # Test the truth value of floating point zero
    
    $x = 0.0;
    if ($x) {
      print "floating point zero is true\n";
    } else {
      print "floating point zero is false\n";
    }
    
  5. #!/usr/bin/perl -w
    
    # Test the truth value of the string "0"
    
    $x = "0";
    if ($x) {
      print "the string \"0\" is true\n";
    } else {
      print "the string \"0\" is false\n";
    }