Control Structures

The foreach loop

We have previously learned how to use the foreach construct for iterating over all elements of an array ("Arrays", slides 2, and 4).

Now we will see how to use the foreach construct to simply repeat a block of code a given number of times.

Example:

foreach (1 .. 15){
  __________________;
  __________________;    # repeat 15 times
  __________________;

}

Example:

foreach (1 .. $n){
  __________________;
  __________________;    # repeat $n times
  __________________;

}

This form of the foreach loop also allows us to iterate over all elements of an array while regarding the indexes of the elements.


Example 1 - read 5 lines from standard input

#!/usr/bin/perl

print "Please enter 5 lines of text\n";

$text = "";

foreach (1 .. 5) {
  my $line = <STDIN>;
  $text .= $line;
}

# do something with the text.
# in this example we will just print it.

print "\n",
      "*******************\n",
      $text,
      "*******************\n";

Example 2 - calculate factorial (n!)

#!/usr/bin/perl

# get number from user

print "Please enter a non-negative integer: ";
my $n = <STDIN>;
chomp ($n);

# calculate result or send error

my $result;

if ($n<0) {       # negative number -> error
  print "Sorry, you entered a negative number.\n";
   
}elsif ($n==0) { # 0! is 1
  $result = 1;
 
}else{            # calculate factorial for 
                    # positive integers
   $result = 1;
   
   foreach $i (1 .. $n) {
      $result *= $i;
   }
   
}

#print result

print "The factorial result is: $result\n";

Example 3 - iterate over an array, using its indexes

#!/usr/bin/perl

my @genes = ("POLR2A", "RCV1", "TP53", "TRK1");

# print genes and their indexes

foreach $i (0 .. $#genes) {
   print "$i. $genes[$i]\n";
}
Output:
0. POLR2A
1. RCV1
2. TP53
3. TRK1


Table of Contents.
Previous | Next.