|
|
|
![]() |
|||||||
for ($i = 0; $i <= $repeats-1; $i++) {body;} |
|||||||
$i=0; do {print("$i\n"); $i++; } while($i < 10);
|
|||||||
New Perl Loops And Syntax
Here's some of the new loops and modified C loops Perl offers.
until $i=0; until($i >= 10) { print($i\n"); } do {} until
$i=0; do { print("$i\n"); } until($i > 10); foreach @mylist=qw(Roger Duane Rerun Dee Momma Shirley); foreach(@mylist) { print("$_ was in What's Happening \n"); } Version 2
@mylist=qw(Roger Dwayne Rerun Dee Momma Shirley); foreach $member (@mylist) { print("$member was on What's Happening \n"); } Each time through the loop, $_ and $member contain a new value. You can also the foreach
with modify the way the array is evaluated when it's in the foreach loop. Here's some examples.
Loop Features And Flow Control
Now here's something that's nice. Perl has some commands that can kick you out of a loop, bring you to the next iteration of the loop while skipping the rest of the code, and re-do the current iteration of the loop.
for($i=0; $i < 20; $i++) { last if ($i==7);
printf("$i \n"); } Yeah, it's a pointless example, but it works. As soon as i equals 7, the loop stops. This command can only
be used on for, foreach, while, and until loops. It will not work with if|unless/else statements or do {} while/until loops. I can understand why it won't work in an if/else because it's not a loop. But do
is and the only reason I can think of why do doesn't work is because the loop control is on the bottom whereas all the others it's on the top. Anyway, I've tried it and it doesn't' work. So that's the end of that. $i=0; while($i < 20) { $i++;
next if ($i == 7); print("$i \n"); } This will print every number from 1 to 20 except for 7. $i=0; while($i < 50) { $i++; redo if (($i**2)%2); print("$i \n"); } This will print out all even squares of numbers 1 to 50. LOOP1: for($i=0; $i < 50; $i++) { LOOP2: for($j=0; $j < 10; $j++)
{ LOOP3: for($k=0; $k < 30; $k++) { last LOOP1 if ($k == (2*$i) == (3*$j));
} } } Yup, this example is pointless, but it shows how labels work. Once k is 6, i is 3, and j is 2, the
last will be called. This will exit out of LOOP1 rather than LOOP3. $i=2; $i++ while ($i <= 10); That should make i equal to 10 without having to put in a set of curly braces. The one thing you can't do is nest single line loops in a single line loop.
|
|||||||
|
|||||||