Bootstrap FreeKB - Perl (Scripting) - Break out of a loop
Perl (Scripting) - Break out of a loop

Updated:   |  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 (break out of a loop)
  • next (move onto next item in a loop)
  • return (break out of a subroutine)

 

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 Buy Me A Coffee



Comments


Add a Comment


Please enter c19651 in the box below so that we can be sure you are a human.