while (condition) {
code block
}
As you can probably figure out, the code block is executed while the condition evaluates to true. As soon as the condition evaluates to false, the code block is passed over and the rest of the file is run. The conditions function exactly the same way as I wrote about in my if post, so if you need to brush up on what a condition is and how it works, go to http://www.perladventures.blogspot.co.uk/2014/04/ifelsifelse.html
Here's an example of how you can use while in your code:
This will give output:
1. my $i = 5; 2. 3. while ($i > 0) { 4. print "$i\n"; 5. $i--; 6. }
5
4
3
2
1
The condition is evaluated before the first iteration so if the condition is initially false, the code block will never be run.
Until
There's also a revers version of while. I've never actually seen it in real code before and it looks just as difficult as unless.
until (condition) {
code block
}
This time, the code black runs while the condition evaluates to false
This will give output:
1. my $i = 1; 2. my $j = 12; 3. 4. until ($i > $j) { 5. print "$i\n"; 6. $i *= 2; 7. }
1
2
4
8
Again, the condition is evaluated before the code block is run. So if your condition initially evaluates to true, the code block will never be run.
The examples I've done are all to do with numbers but you can use pretty much anything you want.
Next in the loops and conditionals mini-series - loop controls
To have 'repeat ... until' loop known from other languages you can use 'do { ... }' construct together with 'until (expr)' as statement modifier:
ReplyDeletedo { ... } until (expr);