Looping


Beginning | Previous | Next

Basics

Most looping constructs in Perl are quite similar to those of C/C++. The one major difference is that Perl always requires opening and closing braces ({}), even if the loop contains only one executable Perl statement.

foreach Loops

The foreach construct is similar to the C shell's foreach thingy. The general syntax is: foreach [$loop_var] (@list) { # expression(s) } This loop will itterate over the entire length of the list, from beginning to end, setting $loop_var to consecutive elements of @list. If $loop_var is omitted, $_ is set. @list ca be any list, including functions that return a list.

for Loops

for loops are identical to their C/C++ counterparts, so the syntax is the very familiar: for (init_expression; loop_condition; loop_expression) { # expression(s) } and as a simple example: for ($i = 0; $i < $length; $i++) { print "inc = $inc[$i]\n"; }

while, do/until and do/while Loops

A while loop has the following syntax: while (expression) { # expression(s) } and will continue until expression becomes true. The do/while loop construct is, again, similar to the C/C++ loops, and has the form: do { # expression(s) } while (expression) You could substitute until (expression) in the do/while loop above for a different flavor of looping (ie, the compliment of the do/while).

Beginning | Previous | Next
Last Modified: $Date: 1997/05/02 07:17:43 $