Perl (Scripting) - Break out of a loop

by
Jeremy Canfield |
Updated: May 09 2023
| Perl (Scripting) articles
Typically, one of the following is used to break out of a loop or to move onto the next item in a loop.
last is used to break out of a loop, whereas return is used to break out of a subroutine.
Let's say you have the following script.
#!/usr/bin/perl
use strict;
use warnings;
my @fruits = qw(Apple Orange Banana Grape);
foreach my $fruit (@fruits) {
print "$fruit \n";
}
Running this script will return the following. Each value in the array was returned.
Apple Orange Banana Grape
In this example, last is placed inside of the loop.
#!/usr/bin/perl
use strict;
use warnings;
my @fruits = qw(Apple Orange Banana Grape);
foreach my $fruit (@fruits) {
print "$fruit \n";
last;
}
Now only the first value in the array is printed.
Apple
Did you find this article helpful?
If so, consider buying me a coffee over at