您的位置:寻梦网首页编程乐园CGI编程Zhanshou's CGI Tutorial

Loop Statements


Perl uses foreach, for, while/do statement to implement loops. Loops allow us to execute a block of code until a certain condition is meet or a predefined number of iterations have been performed.

foreach

The foreach loop consecutively picks up one element from an array of elements one after another and deals with them. The syntax is :
 
    foreach VAR ( LIST ) { 
        STATEMENTS; 
    } 
each time through the loop, VAR is assigned the next element in the LIST, and the STATEMENTS are executed. Here is an example of foreach loop:
    #!/usr/local/bin/perl
    @words=("cat","dog","horse");
    foreach $key(@words){
          print "It is a $key \n";
    }
will get the following result:
It is a cat
It is a dog
It is a horse

for

The for loop is nearly identical to the C for loop.
 
    for ( INITIAL_EXPR ; COND_EXPR ; LOOP_EXPR ) { 
        STATEMENTS; 
    } 
The loop is initialized by evaluating INITIAL_EXPR, iterates while COND_EXPR is true, and evaluates LOOP_EXPR before beginning each subsequent loop.
 
    # an example print number
    for ( $i=1 ; $i<=5 ; $i++ ) { 
        print("$i\n"); 
    } 
will get the following result:
1
2
3
4
5

while/do loop

Syntax:
 
    while ( EXPRESSION ) { 
        STATEMENTS; 
    } 
or
     do { 
        STATEMENTS; 
    } while (EXPRESSION); 

Control Statement

All loops support the following two control statements:
  • last

    Declare that this is the last statement in the loop; completely exit the loop even if the condition is still true, ignoring all statements up to the loop's closing brace.

  • next

    Start a new iteration of the loop
For example, the following code:
        
     for($i=1;$i<=12;$i++){ 
          next if(($i%2)==0);
          last if($i==9);
          print "$i \n";    
     }
will produce this result:
1
3
5
7
Think it over see why it produces the above result.
Previous Page Table of Content Next Page