Perl Control Structures
Conditionals
if ($x > 10) {
print "Greater than 10\n";
} elsif ($x < 10) {
print "Less than 10\n";
} else {
print "Exactly 10\n";
}
# Ternary operator
my $result = $x > 10 ? "big" : "small";
Loops
# While loop
while ($i < 10) {
print "$i\n";
$i++;
}
# For loop
for my $i (0..9) {
print "$i\n";
}
# Foreach loop
foreach my $item (@array) {
print "$item\n";
}
Loop Control
# next - skip to next iteration
# last - exit loop
# redo - restart current iteration
for (1..10) {
next if $_ % 2; # Skip odd numbers
last if $_ == 8; # Stop at 8
print "$_\n";
}
Back to Tutorials