Forum

Learn Perl If Then …
 
Notifications
Clear all

Learn Perl If Then Else statements

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

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 final else

🧠 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

 


   
Quote
Share: