next up previous contents index
Next: Use of $_ Up: Loops Previous: Loops   Contents   Index


Simple for () {}

The first syntax for a loop we will examine is a simple for() loop:
  for $var (LIST) {
    statement_1;
    statement_2;
      .....
  }
In this form, the items in the list are iterated over, with the variable $var taking on the value of the item in the list at the current moment, and all statements in between the left and right curly braces are executed once for each iteration. This is a convenient way to iterate over both array and hash elements:
  my @arr = (1, 5, 10);
  for my $element (@arr) {
    print qq{The current element is now $element\n};
  }

  my %hash = (name => 'Janet', age => 24);
  for my $key (keys %hash) {
    print qq{The key $key has value $hash{$key}\n};
  }


Subsections