Perl 101 (Part 3) - Looping The Loop - Every Comedian Needs An Exit
(Page 6 of 9 )
The "for" loop also comes with a bunch of control statements, which can beused to modify its behaviour. We've listed the important ones below,together with examples:
next:
The "next" statement allows you to jump to the next iteration of the loopwithout executing the remaining statements of the current iteration.Consider this:
#!/usr/bin/perl
for ($counter=1; $counter<=10; $counter++)
{
if($counter == 9)
{
next;
}
print("$counter ");
}
print ("\nHey! Where did 9 go?\n");
print ("Simple. 7 8(ate) 9\n");
print ("Hey, if we were professional comedians, we wouldn't be here,
right?!\n");
Here's what it looks like:
1 2 3 4 5 6 7 8 10
Hey! Where did 9 go?
Simple. 7 8(ate) 9
Hey, if we were professional comedians, we wouldn't be here, right?!
As you can see, 9 is missing - this is because when the value of $counterhits 9, Perl uses the "next" statement to skip to the next iteration of theloop, and so 9 never gets printed.
last:
The "last" statement is used to exit the loop completely. Take a look:
#!/usr/bin/perl
for($counter=1; $counter<=10; $counter++)
{
if($counter == 9)
{
last;
}
print("$counter ");
}
And here's the output:
1 2 3 4 5 6 7 8
redo:
And finally, the redo statement lets you restart a particular iteration ofthe loop:
#!/usr/bin/perl
for($counter=1; $counter<=10; $counter++)
{
print("$counter ");
if($counter == 9 && $flag != 1)
{
$flag=1;
redo;
}
}
In this case, here's what you'll see:
1 2 3 4 5 6 7 8 9 9 10
This article copyright Melonfire 2000. All rights reserved.Next: Grade School >>
More Perl Articles
More By Vikram Vaswani and Harish Kamath, (c) Melonfire