Perl: for, while, Loop

By Xah Lee. Date: . Last updated: .

for-loop

use utf8;

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

while-loop

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

Existing Loop

Here's the most common exit control:

next
Start the next iteration.
last
Exit the loop.
use utf8;
for $xx (1..9) {
  print $xx;
  if ($xx == 4) {
    last;   # exit loop
  }
}   # 1234

Perl, Loop and Iteration