Lesson 13: Loops


3 different types of loops

  • while
  • for
  • foreach

all loops have the same format:

loop-type (){
}

while loops

  • A while loop will continue to execute the code in the while block until the while condition is false
  • Not to be confused with an 'if' statement. An 'if' statement is tested only once. A 'while' statement is continuously tested until it is found to be false

Code:

1
2
3
4
5
my $i=0;
while ($i < 5){
  print "$i\n";
  $i++;
}

Output:

%% ./loops.pl
0
1
2
3
4

if you forget the $i++, the script with be in an endless loop, printing 0 forever until you stop it with 'Control-c'. You must include a statement to change the variable being tested.

for loops

  • A for loop contains the variable initialization ; condition ; update
  • Will continue to execute the code in the for block until the test condition is false

Code:

1
2
3
for (my $i=0 ; $i < 5 ; $i++){
  print $i , "\n";
}

Output:

%% ./loops.pl
0
1
2
3
4

foreach loop

  • especially suited for iterating through each element of an array
  • continues to execute the foreach block code until the list or array has reached the final element
1
2
3
4
my @array = ('apple','bee','cat');
foreach my $element (@array){
  print "$element\n";
}

Output:

%% ./loops.pl
apple
bee
cat

for loops and arrays

  • for loops are also useful for iterating through each element of an array

Code:

1
2
3
4
my @array = ('apple','bee','cat');
for (my $i=0 ; $i < @array ; $i++){
  print $array[$i],"\n";
}

NOTE:

$i < @array means:

Is $i less then the number of elements in @array?


This is the same as $i < scalar @array

Output:

%% ./loops.pl
apple
bee
cat

Exercises

  1. Write a script in which you have a while loop. Execute the while block of code until your test statement is false.
  2. Add a for loop to your script that executes a block of code until the condition is false
  3. Add a foreach loop that iterated through each element of an array and executes a block of code on each element
  4. In your foreach block add a conditional if/elsif/else statement to only do something to each element if it passes specific conditions.

Print Friendly

Leave a Reply

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