Perl: for, while, Loop

By Xah Lee. Date: . Last updated: .

“for” Loop

#-*- coding: utf-8 -*-
# perl

@aa = (1..9); # creates a array 1 to 9
for $xx (@aa) {
    print $xx;
}                               # ⇒ 123456789

“while” Loop

#-*- coding: utf-8 -*-
# perl

$x = 1;
while ($x <= 9) {
  print $x, "\n";
  $x++;
}

Existing Loop

Here's the most common exit control:

#-*- coding: utf-8 -*-
# perl

for $xx (1..9) {
  print $xx;
  if ($xx == 4) {
    last;                       # exit loop
  }
}                               # → 1234