The for and if statements

The for statement allows you to perform the same block of code for a set of values. The for loop takes three components; one to set the initial state, a condition to test the loop variable, and a means of modifying the looping variable.

There are two other looping commands, while and until that evaluate a logical expression and execute a block of code so long as the logical expression is true and false respectively.

The if statement evaluates a logical condition, and if that condition turns out to be true, executes a block of code. The block is delimited by curly brackets, as is the block for the for statement.

More than one condition can be incorporated by using the elsif and else constructs.

There is an unless statement, that could be expressed as an if statement but is cleaner!

Here's as example of basic usage:

#!/usr/local/bin/perl

for($i = 0; $i < 30; $i++){
    if(( $i % 2) == 0){
        print $i, `` is an even number!\n'';
    }
}

Flow through a loop can be modified using the next and last operators. next allows you to skip to the end of the current loop iteration and last lets you go to the end of the block.



Richard Waterman
Fri Jan 22 01:27:29 EST 1999