The <tt>while</tt> statement



next up previous
Next: The for and Up: Flow Control Previous: If-Then-Else

The while statement

Perl's while statement is very versatile. Since Perl's notion of truth is very flexible, the while condition can be one of several things. As in C, Perl conditional statements can be actions or functions.

For instance, the <STDIN> statement with no argument assigns a line of standard input to the $_ variable. To loop until the standard input ends, this syntax is used:

while (<STDIN>)
{
      print "you typed ",$_;
}

In keeping with the recommended beginner practice of including all default arguments, that code would look like this:

while ($_ = <STDIN>)
{
      print "you typed ",$_;
}

As stated before, an array is ``true'' if it has any elements left. For instance:

@users = ("nigel","david","derek","viv");
while (@users)
{
     $user = shift @users;
     print "$user has an account on the system\n";
}

This while loop will continue as long as @users has at least one element. The shift routine pops the first element off the named array and returns it.

Perl has two keywords used for shortcutting loop operations. The next keyword is like C's continue statement. It will immediately jump to the next iteration of innermost loop. The last keyword will break out of the current conditional statement. It is analogous to C's break statement.