Home » Perl Basics
8

Loops

How to create a For loop,

The FOR loop

There is several way to create a “for” loop. The first one is this one.

  for ($i=1; $<=10; $i++) {print “$i\n”;}
  
$i=1 you initialize the value that will serve as reference for the loop.
$i<=10 tell the script to continue as long as $i lower or equal to 10.
$i++ adds 1 to $i each time a loop is done.
{ code} will be executed after each loop. In the case of that script you will have an output of 1,2,3,4,5,6,7,8,9,10.
while the $i is defined inside the “for” loop it will not be reset after each loop. Only when the “for” is entered the first time.
Remember that in order to have a script more upgradable it is advised to use variables whenever you can. If your script is 2000 line you will not want to go through all the code to change the number of file to open from 2 to 3 in each of your functions. Simply create a variable that you will be able to change once if you need to.
Another way is so:
  for ($value1..value2) { code ;}
  
The syntax is reminiscent of the one to print an array and works the same way with the same limitations.
Another way is fo use the foreach function. foreach is design to work with arrays.
  foreach (@name-of-your-array) { print “$_”;}
Perl in that case creates a variable in the foreach loop containing the element of the array that is currently considered. With that variable can be use the element of the array the loop is at.

While / Until

"While" tests the header of the while section and as long as it is true it will execute the code.

  while (condition) {
  Code
  }
while will run as long as the condition is true.
  Until (condition) {
  Code
  }
  
Until" will run until the condition is true.