For and While Loops in Perl

  1. For loops have the general form
    for (initial value, test, increment) { 
      code; 
    }
    
    In this example, we add up the first four numbers and store their value in $n. Notice the recursive assignment $n = $n ... is allowed in Perl.
    $n = 0;
    for ($i = 1; $i < 5; $i++) { 
       $n = $n + $i;
    }
    


  2. Foreach loops run through arrays and have the general form
    foreach $element @array { 
       code; 
    }
    
    and will execute the code for each element of the array. In this example we compute 4 factorial and store it in $n. By writing my $i (instead of just $i) in the foreach loop we declare the variable $i is local (it has limited scope). This means that outside of the foreach loop the variable $i always takes the value 75, while inside the foreach loop the variable $i will take the values in the array (1..4), and the values outside and inside the foreach loop never interfere with each other.
    $i = 75;
    $n = 1;
    foreach my $i (1..4) {
       $n = $n * $i;
    }
    
    Foreach loops can also be used to fill arrays with values.
    @evens = ();
    foreach my $i (0..10) {
       $evens[$i] = 2*$i;
    }
    


  3. While loops have the general form
    while (condition) { 
      code; 
    }
    
    and will continue to execute code as long as the condition remains true. In this example, we increment $i by +1 so long as it is not equal to 5. We could have used < instead of != and gotten the same end result $i = 5;.
    $i = 0;
    while ($i != 5) { $i++; }
    

Online References