Notifications
Clear all
Topic starter 01/08/2025 11:31 pm
In Perl, if-then-else
statements are used to control the flow of your program based on conditions—like giving your code decision-making powers 🧠⚡
🧪 Basic Syntax
if (condition) {
# Code runs if condition is true
} else {
# Code runs if condition is false
}
condition
: Any expression that evaluates to true or false- Perl treats
0
,'0'
,undef
, and empty strings as false; everything else is true
🔍 Example
my $age = 20;
if ($age >= 18) {
print "You're an adult.\n";
} else {
print "You're a minor.\n";
}
- If
$age
is 18 or more, it prints “You’re an adult.” - Otherwise, it prints “You’re a minor.”
🔁 elsif
for Multiple Conditions
my $score = 85;
if ($score >= 90) {
print "Grade: A\n";
} elsif ($score >= 80) {
print "Grade: B\n";
} else {
print "Grade: C or below\n";
}
elsif
lets you check additional conditions- You can chain multiple
elsif
blocks before the finalelse
🧠 Tips
- Always use curly braces
{}
even for single-line blocks—it’s good practice and avoids bugs - Indentation isn’t required by Perl, but it makes your code easier to read
- You can nest
if
statements inside each other for more complex logic