Perl: Loops

Perl supports the following types of loops:

  • for loop
  • foreach loop (and for my loop)
  • while loop
  • until loop
  • do ... while loop
  • nested loops

Perl also supports the following loop control statements:

  • next statement
  • last statement
  • continue statement
  • redo statement
  • goto statement

Example: For loop in Perl


	for (my $i=0; $i <= 5; $i++) {
	   print "$i\n";
	}
	

Output:

  0
  1
  2
  3
  4
  5


Example: Foreach loop in Perl


	foreach my $i (0..5) {
	  print "$i\n";
	}
	

Output:

  0
  1
  2
  3
  4
  5


Example: For my loop in Perl


	for my $i (0..5) {
	  print "$i\n";
	}
	

Output:

  0
  1
  2
  3
  4
  5


Example: while loop in Perl


	my $count = 12;
	 
	while ($count > 0) {
	  print "$count\n";
	  $count -= 2;
	}
	

Output:

  12
  10
  8
  6
  4
  2