How to perform conditional statements and loops in Perl?

In Perl, conditional statements and loops can be implemented using keywords such as if, elsif, else, while, and for. Here are some common examples of conditional statements and loops.

  1. Condition:
my $num = 10;
if ($num > 0) {
    print "Number is positive\n";
} elsif ($num < 0) {
    print "Number is negative\n";
} else {
    print "Number is zero\n";
}
  1. Loop operation.
# 使用while循环打印1到10
my $i = 1;
while ($i <= 10) {
    print "$i\n";
    $i++;
}

# 使用for循环打印1到10
for my $i (1..10) {
    print "$i\n";
}

# 使用foreach循环遍历数组
my @array = (1, 2, 3, 4, 5);
foreach my $element (@array) {
    print "$element\n";
}

In addition to the examples above, Perl also offers more conditional and looping methods such as unless, until, and do while, allowing you to choose the appropriate way to implement conditional checks and loops based on specific needs.

bannerAds