Control Structures for while Loops Web Programming 1

Control Structures: for & while Loops Web Programming 1

Review n Conditional Expression is a key component of Control Structures ► ► The “value” of the conditional expression determines the program flow Syntax: KEYWORD (expression) { statements } • e. g. if ($count<5) { print “count is $countn”; } n Evaluation of Conditional Expression ► ► n Comparison Operators (CO) Compares two things ► ► n Numeric CO: ==, !=, >, >=, <, <= String CO: eq, ne, gt, ge, lt, le Logical Operators Tests for multiple conditions ► n True if the value of the expression is non-zero. False if the value of the expression is zero (or null). AND (&&), OR (II), NOT (!) if Conditional Syntax ► if (condexpr 1) { statements 1 } elsif (condexpr 2) { statements 2 } else { statements 3 } Web Programming 2

while Loop ► Syntax initialization while (exit condition) { statements } ► Typically involves • variable initialization before the loop • exit condition • variable manipulation inside the loop to trigger loop exit $a=“”; while ($a ne “x”) { $a=<STDIN>; chomp $a; print “$an”; } Example script Web Programming 3

for Loop n Iterative Loops are another type of control structures ► n statements are executed fixed number of times Iterative Loops in Perl ► for (initialization; test condition; increment) { statements } e. g. for ($i=1; $i<=5; $i++) { print “$in”; } Example script ► foreach localvar(list expression) { statements } • list expression is an array variable or list • localvar is a scalar variable defined only for the duration of foreach loop à localvar holds list elements in sequential order • iterates through list elements e. g. foreach $i (1, 2, 3, 4, 5) { print “$in”; } Example script Web Programming 4

Loop Control n Ways to control the program flow of Loop block (i. e. Loop Control) ► n last ► typically used with if or unless terminates the loop Example script n next ► skips to the next loop iteration Example script Web Programming 5
- Slides: 5