Control Flow
if, elsif, aur else bilkul waise kaam karte hain jaise zyada tar C-family languages mein karte hain — ek parenthesized condition, phir ek block. C ke bar-aks, braces mandatory hote hain, chahe single statement ho.
use strict;
use warnings;
my $score = 73;
if ($score >= 90) {
print "A\n";
} elsif ($score >= 70) {
print "B\n";
} else {
print "C or below\n";
}
B
Perl mein unless bhi hota hai, jo simply if hai jis ki condition negated hoti hai — "do this unless some condition holds" ke liye idiomatic, aksar if (!...) se zyada naturally parhta hai. Isi tarah, until while hai jis ki condition negated hoti hai.
use strict;
use warnings;
my $age = 15;
print "Minor\n" unless $age >= 18;
my $n = 0;
while ($n < 3) {
print "while: $n\n";
$n++;
}
my $m = 0;
until ($m >= 3) {
print "until: $m\n";
$m++;
}
Minor while: 0 while: 1 while: 2 until: 0 until: 1 until: 2
if aur unless, aur while aur until, dono ka ek postfix form bhi hota hai — upar wala print "Minor\n" unless $age >= 18; exactly wahi hai, ek poora statement jis ke baad us ki condition aati hai, bilkul baghair braces ke. Next: loops and foreach — C-style for loop, list par foreach, aur last/next.
Practice exercise
my $temp = 85 diya gaya hai, agar $temp 80 se zyada ho to "hot" print karein, 60 se zyada ho to "warm", warna "cold".