WHILE and DO WHILE loopings in Perl - How to Use

In this Perl tutorial, we will start studying repetition statements, also called loops, starting with good old while and then getting to know the do while looping.

WHILE looping in Perl

The WHILE loop syntax is as follows:
while( expressiona ){
   # code to run
   # in case expression
   # be true
}
It works like this: we type while, we open parentheses and inside it we put some expression. It can be a value (such as a number, a boolean as true or false) or usually a condition, a conditional test whose result will be true or false.

If the final expression is true, the code inside the WHILE loop braces is executed.
At the end of each execution (we call each round of iteration execution), the expression is evaluated again.

If it remains true, the code continues to be ran and ran ...
The usual thing is that there is something inside the code that will eventually change the conditional test that is being performed so that it becomes false at some point and stops the while execution.

WHILE loops examples in Perl

First, let's learn how to count from 1 to 100 with the WHILE loop.
Let's use the $num variable to store numbers from 1 to 100, and print them on the screen.

The code looks like this:
#!/usr/bin/perl

$num=1;

while($num <= 100){
        print $num, "\n";
        $num++;
}    

First, we initialize the variable with the value 1.
The test we will do is: $num <= 100

In other words: is the variable less than or equal to 100? If so, run the code below ...

In code within the repetition statement, we print the variable.
Then we have to increment it by one, we do it with the operator: ++

Now the value of $num is 2. The while expression is evaluated again, and it will be true again. The code will execute, print, and increment ... and this will happen until $num is 100.

At this value, the test is still true, the print is performed, and when the variable is incremented it becomes 101. Then, in the next test of the while expression, the result will be false and the looping will end.

Let's now do the opposite, a countdown, displaying from 1000 to 1:
#!/usr/bin/perl

$num=1000;

while($num>0){
        print $num, "\n";
        $num--;
}    

Note that we now start with the value 1000, the test is "as long as it is greater than 0" and decrement the variable ($num--).

Awesome ! Powerful, this Perl, isn't it?

DO WHILE looping in Perl

The WHILE loop has a special feature: It only runs the first iteration if the expression in it is TRUE, if it is FALSE, the loop doesn't even begin.

If you want at least one iteration to occur, the test to be run at least once, we recommend using DO WHILE. Its structure is very similar to while:
do{
   # code tobe
   # executed
}while(condition);   

First it does the iteration (DO), only then tests the condition.
If it is true, rerun the code between the braces.

A great utility of the WHILE loop is to display menus.

Menus should be displayed at least once to the user, if they want to exit the program right away, ok, but they should be displayed at least once.

Let's look at an example of a banking app:
#!/usr/bin/perl

do{
        print "Choose an option:\n";
        print "0. Exit\n";
        print "1. Extract\n";
        print "2. Withdraw\n";
        print "3. Transfer\n\n";
        chomp($op = <STDIN>);
}while($op != 0);
We store the user option in the $op variable.

If he types 1, 2, or 3, something specific should happen (call the transfer options, go to the withdrawal screen, etc), then we'll see how to program this in Perl.

Then the menu is displayed again.
And it just stops showing if you type 0 to exit.

See the test: $op! = 0
This means: run this loop while the option is different from 0.

The following code asks for the password for the user.
If correct, it falls into the IF and we warn that it is entering the system.
If it goes wrong, it drops to ELSE and we warn it to try again:
#!/usr/bin/perl

do{
        print "Type the password:\n";
        chomp($password = <STDIN>);

        if($password eq 'rush2112'){
                print "Entering the system...\n";
        }else{
                print "Wrong password, try again.\n\n";
        }
}while($password ne 'rush2112');
Note that the condition is: as long as the password is not equal to "rush2112".

That is, the password is rush2112, if use does not enter the correct password, it will be stuck forever on this screen asking for password ... the only way to enter the system therefore is by entering the correct password.

Note that we place an IF ELSE conditional test inside a DO WHILE control structure, this is quite common in programming, tests and loopings being 'nested' to other flow control structures.

Let's now see how to print from 1 to 100 with DO WHILE:
#!/usr/bin/perl

$num=1;

do{
        print $num, "\n";
        
}while(++$num<=100);
Note the command: ++$num <= 100

This means that the $num variable is incremented at first (since the ++ symbol came before) and only after the variable is used for the conditional test.


Now do: $num++ <= 100
What happens to the result? Why?
Explain in the comments.

No comments:

Post a Comment