Lesson 14: Loop Control


There are functions used to control your loop flow.

  • next
  • last

next

  • next is used to skip any code below the next function and proceed to the next iteration of the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
## this code will only print $i if it is odd
 
my $i=0;
while ($i < 5){
  $i++;
  if ($i % 2 == 0){ ## test for even numbers
    next;
  }
  print "$i\n";
}
# if the $i++ is put at the end, the loop will
# be infinit.  0 is even, next will be executed
# and $i will never increment to 1

Output:

%% ./loop_control.pl
1
3
5

last

  • last is used to end all iterations of the loop.
  • Once the last statement is executed the script will exit the loop block
  • Any code outside the loop block will still be executed.
1
2
3
4
5
6
7
8
9
my $favorite = 'dog';
my @array = ('apple','bee','dog','cat');
foreach my $element (@array){
  print "$element\n";
  if ($element eq $favorite){
    last;
  }
}
print "I looked for my favorite word\n";

Output:

%% ./loop_control.pl
apple
bee
dog
I looked for my favorite word

Exercises

  1. Add the 'next' function to one of your loops from lesson 13
  2. Add the 'last' function to one of your loops from lesson 13

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *