Chapter 6: LoopingA.Learning About the Loop Structure●Loop: a structure that allows repeated execution of a block of statements○Within a looping structure, a Boolean expression is evaluated.○If it is true, a block of statements called the loop body executes and theBoolean structure is evaluated again.➢Loop body: can be a single statement or a block of statementsbetween curly braces, or a block of statements between curlybracesa.As long as the expression is true, the statements in the loopbody continue to executeb.When the Boolean evaluation is false, the loop ends○Iteration: one execution of any loop○While loop: loop-controlling Boolean expression is the first statement inthe loop○For loop: usually used as a concise format in which to execute loops○Do...while loop: the loop-controlling Boolean expression is the laststatement in the loopB.Creating while Loops●While loop: to execute a body of statements continually as long as the Booleanexpression that controls entry into the loop continues to be true○Consists of the keyword while followed by a Boolean expression withinparentheses, followed by the body of the loop●You can use while loop when you need to perform a task either a predeterminedor unpredictable number of times○Definite loopor acounted loop: a loop that executes a specific number oftimes○Indefinite loop: don’t know how many times it will eventually loops●Writing a Definite while Loop○Loop control variable: a variable whose value determines whether loopexecution continues Show
Loop StatementsAll loop statements have an optional while and until StatementsThe The Unlike the A variable declared in the test condition of a while (my $line = <STDIN>) { $line = lc $line; } continue { print $line; # still visible } # $line now out of scope here Here the scope of for Loops The three-part LABEL: for (my $i = 1; $i <= 10; $i++) { … } is like this: { my $i = 1; LABEL: while ($i <= 10) { … } continue { $i++; } } except that there's not really an outer block. (We just put one there to show how the scope
of the If you want to iterate through two variables simultaneously, just separate the parallel expressions with commas: for ($i = 0, $bit = 0; $i < 32; $i++, $bit <<= 1) { print "Bit $i is set\n" if $mask & $bit; } # the values in $i and $bit persist past the loop Or declare those variables to be visible only inside the for (my ($i, $bit) = (0, 1); $i < 32; $i++, $bit <<= 1) { print "Bit $i is set\n" if $mask & $bit; } # loop's versions of $i and $bit now out of scope Besides the normal looping through array indices, $on_a_tty = -t STDIN && -t STDOUT; sub prompt { print "yes? " if $on_a_tty } for ( prompt(); <STDIN>; prompt() ) { # do something } Another traditional application for the three-part for (;;) { … } This is the same as writing: while (1) { … }
If the notion of infinite loops bothers you, we should point out that you can always fall out of the loop at any point with an explicit loop-control operator such as foreach LoopsThe foreach The $sum = 0; foreach $value (@array) { $sum += $value }
for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') { # do a countdown
print "$count\n"; sleep(1);
}
for (reverse 'BOOM', 1 .. 10) { # same thing
print "$_\n"; sleep(1);
}
for $field (split /:/, $data) { # any That last one is the canonical way to print out the values of a hash in sorted
order. See the There is no way with If foreach $pay (@salaries) { # grant 8% raises $pay *= 1.08; } for (@christmas, @easter) { # change menu s/ham/turkey/; } s/ham/turkey/ for @christmas, @easter; # same thing for ($scalar, @array, values %hash) { s/^\s+//; # strip leading whitespace s/\s+$//; # strip trailing whitespace } The loop variable is valid only from within the dynamic or lexical scope of the loop and will be implicitly lexical if the variable was previously declared with If you prefer, you may explicitly declare which kind of variable (lexical or global) to use. This makes it easier for maintainers of your code to know what's really going on; otherwise, they'll need to search back up through enclosing scopes for a previous declaration to figure out which kind of variable it is: for my $i (1 .. 10) { … } # $i always lexical for our $Tick (1 .. 10) { … } # $Tick always global When
a declaration accompanies the loop variable, the shorter Here's how a C or Java programmer might first think to code up a particular algorithm in Perl: for ($i = 0; $i < @ary1; $i++) { for ($j = 0; $j < @ary2; $j++) { if ($ary1[$i] > $ary2[$j]) { last; # Can't go to outer loop. :-( } $ary1[$i] += $ary2[$j]; } # this is where that last takes me } But here's how a veteran Perl programmer might do it: WID: foreach $this (@ary1) { JET: foreach $that (@ary2) { next WID if $this > $that; $this += $that; } } See how much easier that was in idiomatic Perl? It's cleaner, safer, and faster. It's cleaner because it's less noisy. It's safer because if code gets added between the inner and
outer loops later on, the new code won't be accidentally executed, since But write it however you like. TMTOWTDI. Like the Speaking of which, now we can finally say it: Loop ControlWe mentioned that you can put a Loops
are typically named for the item the loop is processing on each iteration. This interacts nicely with the loop-control operators, which are designed to read like English when used with an appropriate label and a statement modifier. The archetypal loop works on lines, so the archetypal loop label is next LINE if /^#/; # discard comments The syntax for the loop-control operators is: last The
Just as you may have as many
The LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with mail header … } The LINE: while (<STDIN>) { next LINE if /^#/; # skip comments next LINE if /^$/; # skip blank lines … } continue { $count++; } The while (<>) { chomp; if (s/\\$//) { $_ .= <>; redo unless eof; # don't read past each file's eof } # now process $_ } which is the customary Perl shorthand for the more explicitly (and tediously) written version: LINE: while (defined($line = <ARGV>)) { chomp($line); if ($line =~ s/\\$//) { $line .= <ARGV>; redo LINE unless eof(ARGV); } # now process $line } Here's an example from a real program that uses all three loop-control operators. Although this particular strategy of parsing command-line arguments is less common now that we have the ARG: while (@ARGV && $ARGV[0] =~ s/^-(?=.)//) { OPT: for (shift @ARGV) { m/^$/ && do { next ARG; }; m/^-$/ && do { last ARG; }; s/^d// && do { $Debug_Level++; redo OPT; }; s/^l// && do { $Generate_Listing++; redo OPT; }; s/^i(.*)// && do { $In_Place = $1 || ".bak"; next ARG; }; say_usage("Unknown option: $_"); } } One more point about loop-control operators. You may have noticed that we are not calling them "statements". That's because they aren't statements--although like any expression, they can be used as statements. You can almost think of them as unary operators that just happen to cause a change in control flow. So you can use them anywhere it makes sense to use them in an expression. In fact, you can even use them where it doesn't make sense. One sometimes sees this coding error: open FILE, $file or warn "Can't open $file: $!\n", next FILE; # WRONG The intent is fine, but the open FILE, $file or warn("Can't open $file: $!\n"), next FILE; # okay However, you might find it easier to read this: unless (open FILE, $file) { warn "Can't open $file: $!\n"; next FILE; } Is a special loop that can be used when a definite number of loop iterations is required?A for loop is a special loop that is used when a definite number of loop iterations is required. For loop have 3 sections, loop variable initialization, testing loop control variable, updating loop control variable.
What type of loop is controlled by the user?Answer: A loop controlled by the user is a type of Incrementing loop.
Which looping structure is appropriate if the number of iterations is not known and you want the code to run at least once?The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.
Is the process of ensuring that a value falls within a specified range?A range check will verify whether input data falls within a predefined range. For example, latitude and longitude are commonly used in geographic data. A latitude value should be between -90 and 90, while a longitude value must be between -180 and 180.
|