Page 103 - Open Soource Technologies 304.indd
P. 103

Open Source Technologies



                   Notes         break;

                                 case ‘n’:
                                 case ‘N’:

                                 print “The answer was no\n”;
                                 break;

                                 default:
                                 print “Error: $answer is not a valid answer\n”;

                                 break;
                                 }
                                                It is important to include a break statement at the end of any code that will
                                                be executed as part of a case statement. Without a break statement, the
                                                program flow will continue to the next case statement and ultimately to the
                                                default statement. In most cases, this will result in unexpected behavior,
                                                likely incorrect!

                                 6.1.7 Loop Control Structures

                                 Loop control structures are used for repeating certain tasks in your program, such as iterating
                                 over a database query result set.
                                 6.1.7.1 While Loops
                                           Statement               Statement List

                                           while (expr) statement  while (expr) :statement list endwhile;

                                 while loops are the simplest kind of loops. In the beginning of each iteration, the while’s truth
                                 expression is evaluated. If it evaluates to true, the loop keeps on running and the statements
                                 inside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop
                                 is skipped. For example, here’s one possible implementation of factorial, using a while loop
                                 (assuming $n contains the number for which we want to calculate the factorial):
                                 $result = 1;

                                 while ($n > 0) {
                                 $result *= $n—;

                                 }
                                 print “The result is $result”;

                                 Loop Control: break and continue
                                 break;

                                 break expr;
                                 continue;

                                 continue expr;




        98                                LOVELY PROFESSIONAL UNIVERSITY
   98   99   100   101   102   103   104   105   106   107   108