Forum

Learn Perl Boolean …
 
Notifications
Clear all

Learn Perl Boolean statements

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

In Perl, Boolean logic is a bit quirky because Perl doesn’t have a dedicated Boolean type like some other languages. Instead, it uses truthy and falsy values based on context 🧪🔍


✅ What’s Considered True in Perl?

Any value that’s not one of the following is considered true:

  • Non-zero numbers (e.g., 1, 3.14)
  • Non-empty strings (even 'false' or '0\n')
  • Strings with spaces (e.g., ' ' or '00')
  • Defined variables with any content
my $x = "false";
if ($x) {
    print "This is true!\n";  # Yes, even 'false' is true!
}

❌ What’s Considered False?

Only these values are false in a Boolean context:

  • 0 (numeric zero)
  • '0' (string zero)
  • '' (empty string)
  • undef (undefined value)
my $y = 0;
if ($y) {
    print "True\n";
} else {
    print "False\n";  # This will print
}

🔄 Boolean Operators

  • ! or not → Logical NOT
  • && or and → Logical AND
  • || or or → Logical OR
my $a = 1;
my $b = 0;

if ($a && !$b) {
    print "a is true and b is false\n";
}

🧠 Fun Quirk

Even the string 'false' evaluates to true! Perl doesn’t care what the string says—it only checks if it’s empty or '0'.



   
Quote
Share: