Exit a Loop with Last
To exit a loop when a condition is met type:
last;
Example:
@dr=("London", "Paris", "Tokyo");
foreach $dr(@dr) {
if ($dr eq "Paris") {
print "Our city: $dr<br>";
last;
}
else {
print "Not our city: $dr<br>";
}
}
Which prints:
Not our city: London
Our city: Paris
-The array @dr contains our cities.
-We loop over the array with
foreach.
-We say "
If $dr equal Paris, print and exit the loop."
The first time through the loop "else" is executed and London gets printed. The second time through the loop, the "if" condition is met, so we print and exit. The third time through the loop never happens.
Copy and Paste Perl Code:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
@dr=("London", "Paris", "Tokyo");
foreach $dr(@dr) {
if ($dr eq "Paris") {
print "Our city: $dr<br>";
last;
}
else {
print "Not our city: $dr<br>";
}
}
exit;