Perl Conditional Statements
if Statement
Basic if Statement
perl
my $age = 18;
if ($age >= 18) {
print "You are an adult\n";
}if-else Statement
perl
my $age = 15;
if ($age >= 18) {
print "You are an adult\n";
} else {
print "You are a minor\n";
}if-elsif-else Statement
perl
my $score = 85;
if ($score >= 90) {
print "Excellent\n";
} elsif ($score >= 80) {
print "Good\n";
} elsif ($score >= 70) {
print "Average\n";
} elsif ($score >= 60) {
print "Pass\n";
} else {
print "Fail\n";
}unless Statement
unless is shorthand for if not, executes the block when condition is false.
Basic unless Statement
perl
my $is_raining = 0;
unless ($is_raining) {
print "We can go out\n";
}unless-else Statement
perl
my $has_ticket = 0;
unless ($has_ticket) {
print "Please buy a ticket first\n";
} else {
print "Please enter\n";
}Nested Usage
perl
my $weather = "sunny";
my $has_money = 1;
unless ($weather eq "rainy") {
print "Weather is good\n";
unless ($has_money) {
print "But no money\n";
} else {
print "Can go shopping\n";
}
}Ternary Operator
Basic Usage
perl
my $age = 18;
my $status = $age >= 18 ? "Adult" : "Minor";
print $status; # AdultNested Ternary Operator
perl
my $score = 75;
my $grade = $score >= 90 ? "A" :
$score >= 80 ? "B" :
$score >= 70 ? "C" :
$score >= 60 ? "D" : "F";
print $grade; # CAssignment and Function Calls
perl
my $user = defined($input_user) ? $input_user : "Guest";
print defined($file) ? $file : "default.txt";given-when Statement (Perl 5.10+)
Basic given-when
perl
use v5.10;
my $day = "Monday";
given ($day) {
when ("Monday") { print "Monday\n"; }
when ("Tuesday") { print "Tuesday\n"; }
when ("Wednesday") { print "Wednesday\n"; }
when ("Thursday") { print "Thursday\n"; }
when ("Friday") { print "Friday\n"; }
default { print "Weekend\n"; }
}Using Regular Expressions
perl
use v5.10;
my $input = "hello world";
given ($input) {
when (/^hello/) { print "Starts with hello\n"; }
when (/world$/) { print "Ends with world\n"; }
when (/hello/) { print "Contains hello\n"; }
default { print "Other\n"; }
}Using Multiple Conditions
perl
use v5.10;
my $number = 5;
given ($number) {
when ([1, 2, 3]) { print "1, 2, or 3\n"; }
when (4) { print "4\n"; }
when ([5, 6, 7]) { print "5, 6, or 7\n"; }
default { print "Other number\n"; }
}Using continue
perl
use v5.10;
my $day = "Wednesday";
given ($day) {
when ("Monday") { print "Weekday\n"; continue; }
when ("Tuesday") { print "Weekday\n"; continue; }
when ("Wednesday") { print "Weekday\n"; continue; }
when ("Thursday") { print "Weekday\n"; continue; }
when ("Friday") { print "Weekday\n"; continue; }
}
print "Continue execution\n";Logical Operators and Conditions
Using && and ||
perl
my $age = 25;
my $has_license = 1;
# Logical AND
if ($age >= 18 && $has_license) {
print "Can drive\n";
}
# Logical OR
my $weather = "sunny";
my $has_umbrella = 0;
if ($weather eq "sunny" || $has_umbrella) {
print "Can go out\n";
}Using and and or
perl
# Low-precedence logical operators
if ($age >= 18 and $has_license) {
print "Can drive\n";
}
if ($weather eq "sunny" or $has_umbrella) {
print "Can go out\n";
}Short-circuit Evaluation
perl
# If first condition is true, second won't execute
my $x = 1;
my $y = 0;
if ($x || ($y = 10)) {
print "Condition is true\n";
}
print "$y\n"; # $y is still 0
# If first condition is false, second won't execute
my $a = 0;
my $b = 0;
if ($a && ($b = 10)) {
print "Condition is true\n";
}
print "$b\n"; # $b is still 0String Comparison
String Equality and Inequality
perl
my $str1 = "hello";
my $str2 = "world";
if ($str1 eq $str2) {
print "Strings are equal\n";
} else {
print "Strings are not equal\n";
}
unless ($str1 eq $str2) {
print "Strings are not equal\n";
}String Magnitude Comparison
perl
my $str1 = "apple";
my $str2 = "banana";
if ($str1 lt $str2) {
print "'$str1' comes before '$str2' in dictionary order\n";
}
if ($str1 le $str2) {
print "'$str1' comes before or is equal to '$str2' in dictionary order\n";
}Defined Check
Using defined
perl
my $value;
if (defined($value)) {
print "Value is defined\n";
} else {
print "Value is undefined\n";
}
my $num = 42;
if (defined($num)) {
print "Numeric value: $num\n";
}Using Defined-or Operator
perl
my $input;
# If $input is undefined, use default value
my $value = $input // "default";
print $value; # default
$input = "user input";
$value = $input // "default";
print $value; # user inputUsing exists to Check Hash Keys
perl
my %hash = (name => "Alice", age => 25);
if (exists $hash{name}) {
print "Key 'name' exists\n";
}
unless (exists $hash{city}) {
print "Key 'city' does not exist\n";
}Complex Conditions
Combining Multiple Conditions
perl
my $age = 25;
my $has_job = 1;
my $has_car = 0;
my $has_license = 1;
if ($age >= 18 && $has_license && ($has_car || $has_job)) {
print "Meets conditions\n";
} else {
print "Does not meet conditions\n";
}Using Parentheses for Clarity
perl
# Clear condition combination
if (($age >= 18 and $has_license) or ($age >= 21 and $has_job)) {
print "Can apply\n";
}De Morgan's Law
perl
# Original condition
if ($age < 18 or $income < 1000) {
print "Not eligible\n";
}
# Using De Morgan's law
unless ($age >= 18 and $income >= 1000) {
print "Not eligible\n";
}Practice Examples
Example 1: Grade System
perl
#!/usr/bin/perl
use strict;
use warnings;
print "Enter score (0-100): ";
chomp(my $score = <STDIN>);
if ($score < 0 || $score > 100) {
print "Invalid score\n";
} elsif ($score >= 90) {
print "A (Excellent)\n";
} elsif ($score >= 80) {
print "B (Good)\n";
} elsif ($score >= 70) {
print "C (Average)\n";
} elsif ($score >= 60) {
print "D (Pass)\n";
} else {
print "F (Fail)\n";
}Example 2: Login Verification
perl
#!/usr/bin/perl
use strict;
use warnings;
my %users = (
"alice" => "password123",
"bob" => "secure456",
"charlie" => "mypass789"
);
print "Username: ";
chomp(my $username = <STDIN>);
print "Password: ";
chomp(my $password = <STDIN>);
if (exists $users{$username} && $users{$username} eq $password) {
print "Login successful! Welcome, $username!\n";
} elsif (!exists $users{$username}) {
print "User does not exist\n";
} else {
print "Incorrect password\n";
}Example 3: Menu Selection System
perl
#!/usr/bin/perl
use strict;
use warnings;
use v5.10;
print "=== Menu ===\n";
print "1. Display Info\n";
print "2. Calculator\n";
print "3. Exit\n";
print "Choose (1-3): ";
chomp(my $choice = <STDIN>);
given ($choice) {
when ("1") {
print "=== Info ===\n";
print "Version: 1.0\n";
print "Author: Your Name\n";
}
when ("2") {
print "=== Calculator ===\n";
print "Enter first number: ";
chomp(my $a = <STDIN>);
print "Enter second number: ";
chomp(my $b = <STDIN>);
print "Sum: " . ($a + $b) . "\n";
}
when ("3") {
print "Goodbye!\n";
exit;
}
default {
print "Invalid choice\n";
}
}Example 4: Leap Year Check
perl
#!/usr/bin/perl
use strict;
use warnings;
print "Enter year: ";
chomp(my $year = <STDIN>);
my $is_leap = 0;
if ($year % 4 == 0) {
if ($year % 100 == 0) {
if ($year % 400 == 0) {
$is_leap = 1;
}
} else {
$is_leap = 1;
}
}
if ($is_leap) {
print "$year is a leap year\n";
} else {
print "$year is not a leap year\n";
}
# Simplified version
my $is_leap_simple = ($year % 4 == 0 and $year % 100 != 0) or ($year % 400 == 0);
print "Simplified check: $is_leap_simple\n";Summary
In this chapter, we learned Perl conditional statements:
- ✅ if/elsif/else statements
- ✅ unless statements
- ✅ Ternary operator
- ✅ given-when statements
- ✅ Logical operators and conditions
- ✅ String comparison
- ✅ Defined checks
- ✅ Complex condition combinations
Next, we will learn Perl Loops.