Block Structures and Loops

This document was written by CS 290W TA David Corcoran and was last modified

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

if, elsif, else

if ( $iAge < 13 ) { print "This student is not yet a teenager. \n"; } elsif ( ( $iAge >= 13 )&&( $iAge <= 17 ) ) { print "This student is a teenager. \n"; } else { print "This student is an adult. \n"; } 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 ) { print "Welcome to Harry's. \n"; } 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 ) { print "You are too young to enter. \n"; $iAge += 1; } The above statement will continue to execute until $iAge is greater than or equal to 21.

Until Statement

$iAge = 13; until ( $iAge >= 21 ) { print "You are too young to enter. \n"; $iAge += 1; } 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++ ) { print "Counting from 0 to 20 $iCount. \n"; } 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 ]