LoopingIn this section we see how to have Perl take actions over and over again. With just a few compact statements we can have our programs do many many things for us.
The 'while' statement is similar in syntax to
the 'if' statement.
The difference is that it executes the body (between { })
repeatedly until the boolean condition is false.
Do you see how the code above works?
What would happen if we didn't add 1 to $i? Make sure that your while loops eventually end - otherwise you will have an INFINITE LOOP!!! It will run forever. Control-C will kill it.
As with the 'if', curly braces are needed even if there is
only one statement inside the body of the while.
The following 'for' statement is exactly equivalent to the above:
The 'for' is sometimes better than the while
because all the elements of loop control are
in one place.
142-144 never 85-87
Loop Control StatementsThe 'next' keyword will continue the next iteration of the loop - either a 'for' or a 'while'. 'last' will exit the loop immediately - either 'for' or 'while'.
Sometimes it is clearer to have the boolean be always true (1)
and use 'last' to exit the loop when a condition is reached.
Note that when using 'next' in a 'for' loop the flow of control is transfered to the increment part. So this will work:
145-146 140-141 87
Increment/Decrement and Assignment OperatorsAll the above have the same effect - the variable is incremented by 1.$i = $i + 1; ++$i; $i++; $i += 1; Decrementing by one is similar: These pairs of statements have the same effect:--$i; These "assignment operators" are sometimes clearer and easier to type and read. For example:$i = $i * 4; $i *= 4; $i += 2; $i = $i + 2; 27-28 62-64 66,86$total_count_of_units = $total_count_of_units + $n; $total_count_of_units += $n;
Mistyped Variable names and -wIt is easy to misytpe variabel names. Using -w on the perl command line will give warnings about such misteaks and several other helpful things as well.It is a good idea to ALWAYS use -w. You can also (since Perl 5.6.0) use the following within your program:#!/usr/bin/perl -w 24-25,264 27-28,284-286 29-30use warnings;
Exercises
|