Contents / Previous / Next


Control Statements: IF ELSE

Conditionals are put to use in IF THEN ELSE. The following are acceptable uses of IF:
 
	if (EXPRESSION ) { 
		STATEMENTS; 
	} 
	 
	if (EXPRESSION ) { 
		# executed if true 
		STATEMENTS; 
	} ELSE { 
		# executed if false 
		STATEMENTS; 
	} 
 
	if (EXPRESSION ) { 
		STATEMENTS; 
	} elsif { 
		STATEMENTS; 
	# optional additional ELSIF's 
	} else { 
		STATEMENTS; 
	}	 
The braces are not optional - requiring braces avoids the dangling else problem.

Perl has no SWITCH statement - it can be imitated several ways, including using ELSIF for each possible case.


Loops

WHILE/DO Loops

In WHILE loop the DO is implied:
 
	while ( EXPRESSION ) { 
		STATEMENTS; 
	} 
If the condition is initially false, the body of the loop will never execute. In the DO-WHILE form, the loop will execute at least once:
 
	do { 
		STATEMENTS; 
	} while (EXPRESSION); 


FOR Loops

The FOR loop it is nearly identical to the C,java,PHP,etc 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. Example "countdown":
 
for ( $i=10 ; $i>=0 ; $i-- ) 
{ 
   print("$i\n"); 
} 

Unlike C, the braces around the block of STATEMETNTS are mandatory


FOREACH Loops

The FOREACH loop iterates over an array or list:
 
	foreach SCALAR ( LIST ) { 
		STATEMENTS; 
	} 
Each time through the loop, SCALAR is assigned the next element in the LIST, and the STATEMENTS are executed.

The braces are mandatory.

Example "re-implement a join":

 
foreach $instrument ("violin","viola","cello","bass") 
{ 
  print($instrument," is lighter than a \n"); 
} 
print("harp\n"); 
Output:
violin is lighter than a 
viola is lighter than a 
cello is lighter than a 
bass is lighter than a 
harp


Loop Flow Control

The loop flow can be modified using next and last:
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
 
# one way to count to 10 
$number = 0; 
while(1) 
{ 
  $number++; 
  if ($number >= 10 )  
  { 
    last; 
  } 
}