Showing posts with label Loopings. Show all posts
Showing posts with label Loopings. Show all posts

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.

Comparison Operators in Perl

Now that we've studied the basics of Perl, let's learn more complex things that will make our scripts even more interesting and useful.

Let's learn how to compare numbers and strings in this Perl tutorial.

Numerical Comparison Operators in Perl

There are 6 comparison operators, which we can use with numbers, in Perl, and they are quite simple as they look like the ones we use in math.

The operators are:
  1. Equal: ==
  2. Not equal: !=
  3. Greater than: >
  4. Less than: <
  5. Greater than or equal to : >=
  6. Less than or equal to: <=
We use them like this:

  • value1 operator value2

And this operation always returns 1 (TRUE ) or empty (FALSE or 0).

For example, run the following script:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
He will return: 1
What print does is the result of operation 2 == 2

This operation is a comparison operation, you're asking: 2 equals 2?
He answers truthfully (represented by 1).

Now test this:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
print "1>2 : ",1>2,"\n";
The result is:
2 == 2: 1
1> 2:

When asked if 1 is greater than 2, it responds with empty, nothing, null ... which is the same as false in Perl.

What if we ask if 1 is different from 2?
We do this with: 1! = 2, and it's a true statement, test the script:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
print "1>2 : ",1>2,"\n";
print "1!=2: ",1!=2,"\n";
Everything worked?

The operation: $ a <$ b
Returns true (1) if $a is less than $b, and false if  a is greater than or even equal to $b.

Already the expression:
$a >= $b
Returns true (1) if $a is greater than or equal to $b and returns false (null) if $a is less than $b.

Finally, the operation:
$a <= $b
Returns 1 if $a is smaller or if $a is equal to $b. If $a is greater than $b it returns false (null).

Perl string comparisons

To compare strings, we will use some small letters, which represent the same thing as the operators above:

  1. Equal to: eq
  2. Not equal to: ne
  3. Greater than: gt
  4. Less than: lt
  5. Greater than or equal to: ge
  6. Less than or equal to: le

That is, the string comparison operators in Perl are:
eq (equal), ne (not equal), gt (greater than), lt (less than), ge (greater than or equal to) and le (less than or equal to).

The comparison is done character by character one by one, comparing to know if the strings are equal or not.

Let's look at some examples:
#!/usr/bin/perl

print "rush eq rush: ", 'rush' eq 'rush',"\n";
print "rush ne Rush: ",'rush' ne 'Rush',"\n";
print "abc gt ab   : ",'abc' gt 'ab',"\n";
print "bc lt bcd   : ",'bc' lt 'bcd',"\n";
Note that in the ASCII standard, uppercase letters come before lowercase:
#!/usr/bin/perl

print "A lt a: ", 'A' lt 'a',"\n";
print "b gt B: ",'B' ne 'b',"\n";
That is, 'A' is less than 'a'
And 'b' is bigger than 'B'

Test the scripts, guys. See the results.
All these operations are like 'questions' to Perl, which answers 1 or null, that is, true or false.

And be careful not to confuse:
$a == 1: is a comparison, is a question '$a equals 1?', generates true or false return

And:
$a = 1: it's an assignment, $a will get the value 1 and period, it's over there.