How to exit for loop in Perl?

by bernard.rippin , in category: Other , 2 years ago

How to exit for loop in Perl?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by kyra.strosin , 2 years ago

@bernard.rippin You can use the last keyword to exit for loop in Perl, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@arr = (1, 2, 3);

for my $num (@arr){
    print "$num\n";
    if ($num eq 2) {
        # exit for loop
         last;
    }
}
# Output: 1 2