Wednesday, 23 April 2014

Loops and conditionals: While/until

This is going to be simple little post about the while statement. It's general format looks like this:

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:
1.   my $i = 5;
2.
3. while ($i > 0) {
4.     print "$i\n";
5.     $i--;
6. }
This will give output:
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
1.   my $i = 1;
2. my $j = 12;
3.
4. until ($i > $j) {
5.     print "$i\n";
6.     $i *= 2;
7. }
This will give output:
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

1 comment:

  1. To have 'repeat ... until' loop known from other languages you can use 'do { ... }' construct together with 'until (expr)' as statement modifier:

    do { ... } until (expr);

    ReplyDelete