1.6 Block Structures and Loops

 

Like other programming languages, Perl supports mostly the same style of Block Statements and Loops.

if, elsif, else

if ( $iAge < 13 ) {<br> &nbsp; print "This student is not yet a teenager. \n";
} elsif ( ( $iAge >= 13 )&&( $iAge <= 17 ) ) {<br> print "This student is a teenager. \n"; <br> } else { print "This student is an adult. \n"; <br> }

Everything looks the same right? Look again. Notice the elsif. Is that a misspelling? No it is not. An else if statement in Perl is actually elsif.

Unless Statement

unless ( $iAge < 21 ) {<br> print "Welcome to Harry's. \n"; <br> }

The above statement only is executed if $iAge >= 21. Basically it is performing the given operation if the statement in the unless block is False.

While Statement

$iAge = 13;

while ( $iAge < 21 ){<br> print "You are too young to enter. \n"; <br> $iAge += 1; <br> }

The above statement will continue to execute until $iAge is greater than or equal to 21.

Until Statement

$iAge = 13;

until ( $iAge >= 21 ) { <br> print "You are too young to enter. \n"; $iAge += 1;<br> }

The above statement will also be executed until $iAge is greater than or equal to 21. This works similar to the Unless Statement in that it executes while the enclosed statement is False.

For Statement


for ( $iCount = 0; $iCount < 21; $iCount++ ) { <br> print "Counting from 0 to 20 $iCount. \n"; <br> }

The above statement sets $iCount to zero and executes until $iCount is less than 21. It increments $iCount during this process. This should count from 0 to 20. Notice how you can embed scalars right into a print statement regardless of their type.

[ Back to Main ]